JavaScript从另一个数组的索引处获取一个数组

3

假设我有一个这样的数组:

var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']

我怎样得到一个数组,告诉我它们每个位置的索引?例如:
var reds = [1,2,3,5], blues = [0,4,6,7]

到目前为止,我尝试使用 indexOf(); 函数,但如果存在多个匹配项,它将只返回其中一个值。


当使用for循环时,只需检查红色或蓝色,然后将其推入红色和蓝色的数组中,然后您就有了红色和蓝色的索引,非常简单。 - Ramo Toric
6个回答

8
你可以使用颜色作为属性,将所有索引收集到一个对象中。
这种方法具有以下特点:
  • 经典的 for语句 用于迭代索引,

  • 逻辑空值赋值 ??= 用于检查属性并在未给定时分配一个数组,

  • Array#push 用于将索引插入以颜色命名的数组中。

const
    colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'],
    indices = {};

for (let i = 0; i < colors.length; i++) {
    (indices[colors[i]] ??= []).push(i);
}

console.log(indices);


3
你可以使用 forEachfor loop 来获取元素和索引,并将它们推入对应的数组中。

var colors = ["blue", "red", "red", "red", "blue", "red", "blue", "blue"];

const reds = [];
const blues = [];

colors.forEach((color, index) => {
  if (color === "red") reds.push(index);
  else if (color === "blue") blues.push(index);
});

console.log(reds);
console.log(blues);


0

你也可以使用 reduce 构建一个对象,其中属性是你的颜色,值是一个包含索引的数组

const colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'];

const indices = colors.reduce((acc, color, index) => {
    return !acc[color] ? 
             { ...acc, [color]: [index]} :
             { ...acc, [color]: [...acc[color], index] }
}, {})

console.log(indices);


0

Nina Scholz的答案看起来不错。我想提供另一种方法来帮助你。

你可以使用Array#reduce来解决它,具有最高性能的O(n)时间复杂度,如下所示:

const colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']

const result = colors.reduce((acc, color, index) => {
  acc[color] ??= [];
  acc[color].push(index);
  
  return acc;
}, {});
console.log(result);


我刚刚添加了一个答案来帮助你。请看一下 ^^!@lmg1114 - Nguyễn Văn Phong

0

我认为这个答案会比其他答案更容易理解:

var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'];

var reds = [];
var blues = [];

for(var i = 0; i < colors.length; ++i)
{
    if(colors[i] == 'red')
    {
        reds.push(i);
    }
    else if(colors[i] == 'blue')
    {
        blues.push(i);
    }
}

-1
let arr1 = ['blue', 'red', 'blue', 'red', 'red', 'blue', 'blue'];

const redElements = arr1.filter(x => x == 'red');

const blueElements = arr1.filter(x => x == 'blue');

Filter 返回一个数组;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接