Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 45532  / 13 Years ago, fri, august 12, 2011, 12:00:00

I have an array of elements



[page=4, sortOrder=asc, datePosted=all-time]


Using javascript or jquery I want to find the index of the element which begins sortOrder= . I will not know the full string of this element at compile time, just the sortOrder= part.



I'm assuming that this can be done without the need to iterate over the array and perform item.match(sortOrder=), but maybe I am wrong.



Thanks for any help.


More From » jquery

 Answers
9

If you want to get the value inside an array that matches a specific regex:



...to get the value of the first match only, you can use find()



const array = [page=4, sortOrder=asc, datePosted=all-time, sortOrder=desc];
const match = array.find(value => /^sortOrder=/.test(value));
// match = sortOrder=asc


...to get an array of all match results, you can use filter()



const array = [page=4, sortOrder=asc, datePosted=all-time, sortOrder=desc];
const matches = array.filter(value => /^sortOrder=/.test(value));
// matches = ['sortOrder=asc', 'sortOrder=desc'];


...to get the index of the first match, you can use findIndex()



const array = [page=4, sortOrder=asc, datePosted=all-time, sortOrder=desc];
const index = array.findIndex(value => /^sortOrder=/.test(value));
// index = 1;


If you are not using ES6, here's the code in ES5.


[#90649] Thursday, August 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;