Index of All Matches

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring the indexOfAll function in JavaScript. This function allows us to find all indexes of a given value in an array. By using the Array.prototype.reduce() method, we can easily loop over the elements of an array and store the indexes for matching elements. This lab will provide hands-on experience with this useful function and its implementation in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28388{{"`Index of All Matches`"}} javascript/data_types -.-> lab-28388{{"`Index of All Matches`"}} javascript/arith_ops -.-> lab-28388{{"`Index of All Matches`"}} javascript/comp_ops -.-> lab-28388{{"`Index of All Matches`"}} javascript/higher_funcs -.-> lab-28388{{"`Index of All Matches`"}} javascript/spread_rest -.-> lab-28388{{"`Index of All Matches`"}} end

All Matches Index

To find all indexes of val in an array, use Array.prototype.reduce() to loop over the elements and store the indexes for matching elements. If val never occurs, an empty array is returned.

const indexOfAll = (arr, val) =>
  arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

Example usage:

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0, 3]
indexOfAll([1, 2, 3], 4); // []

To start practicing coding, open the Terminal/SSH and type node.

This is an index of all matches.

Summary

Congratulations! You have completed the Index of All Matches lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like