javascript - 使用数组二元素查找和存储数组一的索引,并将数组一的所有索引存储在数组 3 中
问题描述
我有这样的主数组,虽然它不是完整的数组,但那是数组的格式
newarr: Array(1)
0: Array(239)
[0 … 99]
0: i {transformMatrix: null, fill: "#FFFFFF", dirty: false, stroke: "#000000", strokeWidth: 0.172, …}
1: i {transformMatrix: null, fill: "#000000", dirty: false, stroke: "#000000", strokeWidth: 0.172, …}
2: i {transformMatrix: null, fill: "#FFFFFF", dirty: false, stroke: "#000000", strokeWidth: 0.172, …}
3: i {transformMatrix: null, fill: "#0000FF", dirty: false, stroke: "#000000", strokeWidth: 0.172, …}
4: i {transformMatrix: null, fill: "#FFFFFF", dirty: false, stroke: "#000000", strokeWidth: 0.172, …}
5: i {transformMatrix: null, fill: "#FFFFFF", dirty: false, stroke: "#000000", strokeWidth: 0.172, …}
第二个数组是我保存数组一中所有唯一颜色的地方,它看起来像这样
uniqueColors: Array(1)
0: "#FFFFFF"
1: "#000000"
2: "#0000FF"
length: 1
__proto__: Array(0)
现在我想使用发送数组元素来查找搜索数组一并在第三个数组中以组形式保存相同的颜色索引。
解决方案
此代码执行两个步骤:
arr1 = [{
transformMatrix: null,
fill: "#FFFFFF",
dirty: false,
stroke: "#000000",
strokeWidth: 0.172
},
{
transformMatrix: null,
fill: "#000000",
dirty: false,
stroke: "#000000",
strokeWidth: 0.172
},
{
transformMatrix: null,
fill: "#FFFFFF",
dirty: false,
stroke: "#000000",
strokeWidth: 0.172
},
{
transformMatrix: null,
fill: "#0000FF",
dirty: false,
stroke: "#000000",
strokeWidth: 0.172
},
{
transformMatrix: null,
fill: "#FFFFFF",
dirty: false,
stroke: "#000000",
strokeWidth: 0.172
},
{
transformMatrix: null,
fill: "#FFFFFF",
dirty: false,
stroke: "#000000",
strokeWidth: 0.172
}
]
dupe = new Set()
arr2 = arr1.filter(({fill}) => {
if (dupe.has(fill)) {
return false
} else {
dupe.add(fill)
return true
}
})
obj = arr2.reduce((acc1, {fill:f1}) => {
acc1[f1] = arr1.reduce((acc2, {fill:f2}, i) => f1 === f2 ? [...acc2, i] : acc2, [])
return acc1
}, {})
console.log(obj)
- 过滤掉所有重复项
arr1
并将其余的返回到arr2
,使用一个集合来记录重复项。 - 将数组缩减为一个对象,其中每个值都是 arr1 的缩减版本,仅返回索引。
推荐阅读
- sql - 如何使用声明将 where 子句和/或 order by 添加到更新语句
- c# - 满足条件时显示 Photon Room(4 个玩家)中的一个玩家的字符串
- haskell - 如何在不导入任何内容的情况下使用模式匹配在 Haskell 中获取字符串中空行的索引?
- javascript - 如何将模态表单组件打开功能分配给任何其他按钮组件
- django - django查询,注解一连串相关模型
- javascript - 如何修复未定义的错误处理 node.js
- python-3.x - 推荐的 lm 数据格式 格式化创建 tfrecords 文件以微调 gpt
- android - Google Fit 集成问题 Android
- python - 如何安装特定版本的 pyenv?
- oracle-sqldeveloper - 如何在 Oracle SQL Developer 应用程序中打开 .db 文件