假设我有一个这样的数组:
var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']
我怎样得到一个数组,告诉我它们每个位置的索引?例如:
var reds = [1,2,3,5], blues = [0,4,6,7]
到目前为止,我尝试使用 indexOf();
函数,但如果存在多个匹配项,它将只返回其中一个值。
假设我有一个这样的数组:
var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']
var reds = [1,2,3,5], blues = [0,4,6,7]
到目前为止,我尝试使用 indexOf();
函数,但如果存在多个匹配项,它将只返回其中一个值。
经典的 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);
forEach
,for 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);
你也可以使用 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);
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);
我认为这个答案会比其他答案更容易理解:
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);
}
}
let arr1 = ['blue', 'red', 'blue', 'red', 'red', 'blue', 'blue'];
const redElements = arr1.filter(x => x == 'red');
const blueElements = arr1.filter(x => x == 'blue');
Filter 返回一个数组;