Jmainol
Jmainol

Reputation: 437

Using for example filter() method, how can I return the elements that meet the condition and its index value at the same time?

Here a code as an example:

const nums = [1, 1, 3, 2, 2, 2, 2, 2, 2, 2];

    oddArr = arrNum.filter(function(num,index){
      return num % 2 != 0
    })

    evenArr = arrNum.filter(function(num,index){
      return num % 2 === 0
    })

Here I would like to return the new array with the original index of each element that meet the condition. I tried placing a , after the condition (num % 2 === 0) but nothing

In case of looking for odds number, I would like to get an output like this (bold data refers to the index of that number in the original array: [1,0,1,1,3,2] Maybe get an object for each result would be better. Something like this:

[
{1,0},
{1,1},
{3,2}
]

I dont even know if its possible,but I wonder because this other code effectively works:

function array_odd_even_position(a) {
   return a.filter((num,index) => console.log(num,index));
}

array_odd_even_position([1, 1, 3, 2, 2, 2, 2, 2, 2, 2])

Upvotes: 2

Views: 297

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122087

Since filter can only filter elements and you need both filter and to modify returned values you could use reduce method and do the both in one go.

const nums = [1, 1, 3, 2, 2, 2, 2, 2, 2, 2];

const { odd, even } = nums.reduce((r, e, i) => {
  let key = (e % 2 == 0) ? 'even' : 'odd';
  r[key].push(i)
  return r
}, { odd: [], even: [] })


console.log(odd)
console.log(even)

Upvotes: 2

deceze
deceze

Reputation: 522500

filter by itself isn't helpful here, since it will always return the values of the array, never its indexes. However, this'll do:

oddIndexes = arrNum.map((_, idx) => idx).filter(idx => arrNum[idx] % 2)

First map your array to an array of indexes, then filter those. You could use reduce to do it in one iteration:

oddIndexes = arrNum.reduce((acc, n, idx) => {
    if (n % 2) {
        acc.push(idx);
    }
    return acc;
}, []);

Upvotes: 3

Related Questions