0

I am passing a number to find all indexes in the array where this number located, but the following implementation returns only a single index not all of them.

I wonder what I am missing.

findNumberIndexes (givenNumber : number)
{
   var inds = array.findIndex(index=> index === givenNumber)
}

For example:

array = [1,5,7,2,3,4,3,2]
givenNumber : 2
expected output : [3,7]
casillas
  • 16,351
  • 19
  • 115
  • 215
  • 1
    Please read the 1st sentence of [this doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) and pay attention to words in bold. – PM 77-1 Sep 18 '18 at 19:02

1 Answers1

-1

array.map((e, i) => {if(e === givenNumber) { return i }}).filter(x => x!==undefined);

e is for element, and i is the index. So map(e, i) returns all the indices where element is equal to givenNumber.filter(x=>x) removes all the undefined values.

edit: from filter(x=>x) to filter(x=>x!==undefined)

Peter Kim
  • 1,929
  • 14
  • 22