如何在JavaScript及Lodash中通过字符串值获取数组索引(示例[0,2])
Hey there! Let's figure out how to get the indices of specific string values in an array—like getting [0,2] from an array where those positions hold your target string. I'll walk you through both vanilla JavaScript and Lodash solutions so you can pick what works best for you.
First, let's start with plain JS since you don't need any external libraries here. The core idea is to iterate over the array, check each element against your target string, and collect the indices where they match.
Option 1: Using forEach
This is straightforward and easy to read:
const fruits = ["apple", "banana", "apple"]; const targetStr = "apple"; const matchingIndices = []; fruits.forEach((fruit, index) => { if (fruit === targetStr) { matchingIndices.push(index); } }); console.log(matchingIndices); // Output: [0, 2]
Option 2: Using reduce
If you prefer a more functional approach, reduce lets you build the result array in one go:
const fruits = ["apple", "banana", "apple"]; const targetStr = "apple"; const matchingIndices = fruits.reduce((acc, fruit, index) => { return fruit === targetStr ? [...acc, index] : acc; }, []); console.log(matchingIndices); // Output: [0, 2]
If you're already using Lodash in your project, it offers some handy utilities to make this even cleaner.
Option 1: Using _.reduce
Lodash's reduce works just like the native one, but it's consistent across older environments if that's a concern:
const _ = require('lodash'); // Make sure Lodash is installed and imported const fruits = ["apple", "banana", "apple"]; const targetStr = "apple"; const matchingIndices = _.reduce(fruits, (acc, fruit, index) => { if (fruit === targetStr) { acc.push(index); } return acc; }, []); console.log(matchingIndices); // Output: [0, 2]
Option 2: Using _.entries + _.filter + _.map
This chain combines Lodash's collection methods to first get key-value pairs, filter matches, then extract indices:
const _ = require('lodash'); const fruits = ["apple", "banana", "apple"]; const targetStr = "apple"; const matchingIndices = _.map( _.filter(_.entries(fruits), ([_, value]) => value === targetStr), ([index]) => parseInt(index) ); console.log(matchingIndices); // Output: [0, 2]
Bonus: Match multiple target strings
If you need to find indices for more than one string (e.g., both "apple" and "banana"), just adjust the condition:
// Vanilla JS example const targets = ["apple", "banana"]; const matchingIndices = fruits.reduce((acc, fruit, index) => { return targets.includes(fruit) ? [...acc, index] : acc; }, []); console.log(matchingIndices); // Output: [0, 1, 2]
内容的提问来源于stack exchange,提问作者Gautham Shetty

