1
const jumbledNums = [123, 7, 25, 78, 5, 9]; 

const lessThanTen = jumbledNums.findIndex(num => {
  return num < 10;
});

Hi, my problem is that this snippet is returning only first met index of element meeting condition num < 10 , but I want to save all indexes meeting condition into new array. From what I have read on Mozilla documentation of .findIndex(), it doesn't check other elements after it finds an element which meeting a condition. Is there any way I can reiterate .findIndex over every element in the array (e.g. using .map()) or I need to use another method to do it?

gudok
  • 4,029
  • 2
  • 20
  • 30
Shimi Shimson
  • 990
  • 9
  • 10
  • 1
    Possible duplicate of [How to find index of all occurrences of element in array?](https://stackoverflow.com/questions/20798477/how-to-find-index-of-all-occurrences-of-element-in-array) – sadrzadehsina Dec 25 '18 at 15:01
  • A question you linked as a possible duplicate asks for indexes of all occurrences of an element, when I am asking for indexes of all elements which are meeting condition in this case num<10. – Shimi Shimson Dec 26 '18 at 10:00

3 Answers3

2

Using Array#reduce()

const jumbledNums = [123, 7, 25, 78, 5, 9];

const lessThanTen = jumbledNums.reduce((a, c, i) => (c < 10 ? a.concat(i) : a), [])

console.log(lessThanTen)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • It is working, but I don't understand code. You are checking values by condition c < 10, alright. But why merging indexes with accumulator is working? – Shimi Shimson Dec 26 '18 at 10:31
1

You could map first either the index if smaller than ten or -1 then filter the index array for valid indices.

const
    jumbledNums = [123, 7, 25, 78, 5, 9],
    lessThanTen = jumbledNums
        .map((v, i) => v < 10 ? i : -1)
        .filter(i => i !== -1);

console.log(lessThanTen);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

you can use array.filter, which will return a new array which will check the condition. To get the values

But array.filter doesn't return index, so you can use array.map, which will create a new array and you can use array.filter to remove the undefined cases.

I hope this will solve the issue.

const jumbledNums = [123, 7, 25, 78, 5, 9]; 

const lessThan10 = jumbledNums.filter(o => o<10)

console.log("array with less than 10", lessThan10)

const lessThan10Indexes = jumbledNums.map((o,i) =>{ 
  return o < 10 ? i : undefined
}).filter(o => o)

console.log("array with less than 10 Indexes", lessThan10Indexes)
Learner
  • 8,379
  • 7
  • 44
  • 82