首页 > 解决方案 > 使用数组二元素查找和存储数组一的索引,并将数组一的所有索引存储在数组 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)

现在我想使用发送数组元素来查找搜索数组一并在第三个数组中以组形式保存相同的颜色索引。

标签: javascriptarrays

解决方案


此代码执行两个步骤:

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)

  1. 过滤掉所有重复项arr1并将其余的返回到arr2,使用一个集合来记录重复项。
  2. 将数组缩减为一个对象,其中每个值都是 arr1 的缩减版本,仅返回索引。

推荐阅读