首页 > 解决方案 > 使用JS将对象数组转换为包含具有相同值的对象的数组数组?

问题描述

我正在尝试将对象数组转换为包含具有相同检测属性值的对象的数组数组。

并且检测属性的不同值将是转换数组索引的边界。

const arr = [
  {fruit: "apple", detect: 0},
  {fruit: "orange", detect: 1},
  {fruit: "grape", detect: 1},
  {fruit: "banana", detect: 1},
  {fruit: "mango", detect: 0},
  {fruit: "strawberry", detect: 0},
  {fruit: "kiwi", detect: 1},
  {fruit: "melon", detect: 1},
  {fruit: "peach", detect: 0},
  {fruit: "blueberry", detect: 0},
  {fruit: "plum", detect: 1},
];

变量 arr 具有具有日期检测属性和值的对象数组。

我想将此数据更改为具有相同值但由检测值 0 索引的数组数组。

 const convertedArr = [
  [
    {fruit: "orange", detect: 1},
    {fruit: "grape", detect: 1},
    {fruit: "banana", detect: 1},
  ],
  [
    {fruit: "kiwi", detect: 1},
    {fruit: "melon", detect: 1},
  ],
  [
    {fruit: "plum", detect: 1},
  ]
];

如您所见,水果橙色是第一个检测值为 1 的属性,convertedArr 的第一个索引由橙色香蕉组成,它位于检测值为 0的芒果属性之前。

第二个指数是草莓指数之后的猕猴桃甜瓜的性状,然后是桃子

我认为这个问题可以使用while和其他循环方法来解决,但使用它有点难以理解。

标签: javascriptarrays

解决方案


您可以使用两个数组的一个来跟踪最终结果,另一个来跟踪检测到 1 的连续值。

  • 如果检测为零并且临时长度大于0,则循环遍历数组,将值添加到最终值
  • 否则将值添加到 temp 以累积连续检测 1
  • 最后检查循环后是否有任何元素留在 temp 中,将其添加到 final

const arr = [{fruit: "apple", detect: 0},{fruit: "orange", detect: 1},{fruit: "grape", detect: 1},{fruit: "banana", detect: 1},{fruit: "mango", detect: 0},{fruit: "strawberry", detect: 0},{fruit: "kiwi", detect: 1},{fruit: "melon", detect: 1},{fruit: "peach", detect: 0},{fruit: "blueberry", detect: 0},{fruit: "plum", detect: 1},];

let final = []
let temp = []

for (let element of arr) {

  // add value to final array when detect is 0 and temp.length > 0

  if ( element.detect === 0 ) {
    if ( temp.length ) {
      final.push(temp)
    }
    temp = []
  } else {
    temp.push(element)
  }
}

// to handle an edge case where we have detect 1 at end of array

if (temp.length) {
  final.push(temp)
}

console.log(final)


推荐阅读