How can I get an Array’s Index number?

Asked

Viewed 73 times

2

How can I acquire the number of elements that has the value of day of 5. This would have to return me another Array, for the manipulation to become more dynamic.

This is the Array I have based on:

let arr = [ 
   {name: "Salário", amount: 150000, day: 5},
   {name: "Internet", amount: -11590, day: 10},
   {name: "Teste", amount: 15000, day: 5},
]

2 answers

3


Using the method reduce, you return an array with the index that has the day equal to 5. We do a check with if (obj.day === 5), we have the code below:

let arr = [ 
   {name: "Salário", amount: 150000, day: 5},
   {name: "Internet", amount: -11590, day: 10},
   {name: "Teste", amount: 15000, day: 5},
];

const indexOfFive = arr.reduce(function(acc, obj, index) {
    if (obj.day === 5)
        acc.push(index);

    return acc;
}, []);

console.log('Posições que tem o day igual a 5: ', indexOfFive);

To reuse code, the reduce should be within a function.

  • a doubt, the reduce will go through all the elements, even if I find in the first right?

  • 1

    @Ricardopunctual that’s right. That wasn’t the requirement of the question? "I need to know the position or index, of the elements that has the day value: 5" , then are several indices

  • you’re right I didn’t notice it, I’ll remove the answer because it makes no sense

0

With Array.prototype.map() build a Array the indices of the arr whose property value day be equal to 5 and for the other values complete with null. From the resulting array remove entries null with Array.prototype.filter().

let arr = [ 
   {name: "Salário", amount: 150000, day: 5},
   {name: "Internet", amount: -11590, day: 10},
   {name: "Teste", amount: 15000, day: 5},
]

console.log(
   arr.map((e, i) => (e.day == 5)? i: null)     //Cria um array com os índices dos elementos 
                                                //cujo day == 5 e null para os demais.
      .filter(e=> e !== null)                   //Remove os nulls do resultado.
)

  • +1 I do not know why the negative vote! The answer is correct, because that was the expected result.

  • @Cmtecardeal, haters. I have to the mounds.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.