I build an array with the following code:
var intestColonne = [];
$('.tbi').find('tr:first th').each(function(){
intestColonne.push(($(this).children('select').val()));
});
//intestColonne=intestColonne.pop(); //if this row is parsed the array becomes undefined
Now I want to check if there are multiple entries of a specific value in the array:
if(intestColonne.filter(x => x === "importo").length>1){
//check the index of each "importo" element
//store it into variables
//remove all the other "importo" leaving only the first (lowest index)
}
I am stuck at the first step since I haven’t found a specific function that may return all the indexes of the "importo" value.
indexOf
will return the first index, lastIndexOf
will return the last. Using indexOf I can specify where to start looking from but this will hardly satisfy my goal.
Isn’t there another type of search I can use?
3
Answers
You can use
map
to get the indexes of the elements beforefilter
.Alternatively, use
Array#reduce
.You can use the .map() method to create an array of all the indexes of a specific value in the array. Here is an example:
This will create an array importoIndexes containing all the indexes of the value "importo" in the intestColonne array.
You can then use the .slice() method to remove all the other "importo" leaving only the first (lowest index)
Javascript array filter method’s second argument supplies index of an element. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
So you can get index of first element using indexOf and then filter it: