Home > Software design >  get the index of two elements and manipulate the array accordingly
get the index of two elements and manipulate the array accordingly

Time:01-25

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?

CodePudding user response:

You can use map to get the indexes of the elements before filter.

intestColonne.map((x, i) => x === 'importo' ? i : null).filter(x => x != null);

Alternatively, use Array#reduce.

intestColonne.reduce((acc, curr, i) => {
    if (curr === 'importo') acc.push(i);
    return acc;
}, []);

CodePudding user response:

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:

var importoIndexes = intestColonne.map((value, index) => value === "importo" ? index : '').filter(String);

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)

intestColonne = intestColonne.slice(0, importoIndexes[0]).concat(intestColonne.slice(importoIndexes[0]   1));

CodePudding user response:

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:

const index = intestColonne.indexOf("importo");
const result = intestColonne.filter( (o,i) => o !== "importo" || i === index );
  • Related