JavaScript Array Filter to get Indices

September 16, 2019

JavaScript’s filter() array method is awesome for pulling out just the values that you want. What if instead of getting those values though, you need to get the array indices for those values instead? reduce() can be used for that purpose, as illustrated by the example below:

const cars = [
{make: "ford", model: "mustang"},
{make: "toyota", model: "camry"},
{make: "ford", model: "fiesta"},
{make: "chevrolet", model: "volt"},
{make: "ford", model: "escape"},
{make: "chrysler", model: "pacifica"},
const fordCarIndices = cars.reduce((fordCarIndices, field, index) => {
if (field.make === "ford") {
return fordCarIndices
}, [])
// Output: [0, 2, 4]

Kellen Mace

Written by Kellen Mace, who lives in Rochester Hills, MI and builds cool stuff on the web. About Kellen // Follow him on Twitter →