You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

Vanilla JavaScript Implementation

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]
Lodash Implementation

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:46:12