lmg*_*114 3 javascript arrays sorting filter
假设我有一个这样的数组:
var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']
Run Code Online (Sandbox Code Playgroud)
我如何获得一个数组,告诉我每个人的位置?例如:
var reds = [1,2,3,5], blues = [0,4,6,7]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试使用该indexOf();
函数,但如果有多个匹配项,它只会返回 1 个值。
您可以使用颜色作为属性收集对象中的所有索引。
这种方法的特点
迭代索引的经典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);
Run Code Online (Sandbox Code Playgroud)