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:
Flowchart:
![flowchart: Get all indices of val in an array. If val never occurs, returns [].](https://www.w3resource.com/w3r_images/javascript-basic-exercise-flowchart-216-1.png)
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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join