w3resource

JavaScript: Get all indices of values in an array

JavaScript fundamental (ES6 Syntax): Exercise-216 with Solution

Write a JavaScript program to get all val indices in an array. If val never occurs, return [].

  • Use Array.prototype.reduce() to loop over elements and store indexes for matching elements.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

console.log(indexOfAll([1, 2, 3, 1, 2, 3], 1));
console.log(indexOfAll([1, 2, 3], 4));

Sample Output:

[0,3]
[]

Pictorial Presentation:

JavaScript Fundamental: Get all indices of values in an array.

Flowchart:

flowchart: Get all indices of val in an array. If val never occurs, returns [].

Live Demo:

See the Pen javascript-basic-exercise-216-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get all the elements of an array except the last one.
Next: Write a JavaScript program to check if the given number falls within the given range.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.