[英]Javascript getting an array from the index of another array
假设我有一个这样的数组:
var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']
我如何得到一个数组来告诉我他们每个人的 position 是什么? 例如:
var reds = [1,2,3,5], blues = [0,4,6,7]
到目前为止,我已经尝试使用indexOf();
function 但如果有多个匹配项,则只会返回值中的 1 个。
您可以收集 object 中的所有索引,并将颜色作为属性。
这种方法的特点
用于迭代索引的经典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);
我认为这比其他答案更容易理解:
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);
}
}
您还可以使用reduce
构造一个 object ,其中属性是您的 colors ,值是带有索引的数组
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);
let arr1 = ['blue', 'red', 'blue', 'red', 'red', 'blue', 'blue'];
const redElements = arr1.filter(x => x == 'red');
const blueElements = arr1.filter(x => x == 'blue');
过滤器返回一个数组;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.