w3resource

JavaScript: Get all indices of values in an array

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

Indices of Value in Array

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:

// Define a function 'indexOfAll' that takes an array 'arr' and a value 'val' as input
const indexOfAll = (arr, val) =>
  // Use the 'reduce' method to iterate over the elements of the array
  arr.reduce((acc, el, i) => 
    // If the current element equals the value 'val', append its index to the accumulator array 'acc'
    // Otherwise, return the accumulator array 'acc' unchanged
    (el === val ? [...acc, i] : acc), 
    // Set the initial value of the accumulator array 'acc' as an empty array
    []);

// Test the 'indexOfAll' function with sample inputs
console.log(indexOfAll([1, 2, 3, 1, 2, 3], 1));
// Output: [0, 3]
console.log(indexOfAll([1, 2, 3], 4));
// Output: []

Output:

[0,3]
[]

Visual 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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-216.php