javascript - 使用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和其他循环方法来解决,但使用它有点难以理解。
解决方案
您可以使用两个数组的一个来跟踪最终结果,另一个来跟踪检测到 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)
推荐阅读
- json - Perl - 从 decode_json 输出访问数据
- r - 如何在 r 中为我的 GNgraph 提取成员向量?
- python - 在 TensorFlow 中查找(许多)稀疏(但块对角线)矩阵的逆矩阵
- database - 是否可以创建一个保留原始表中已删除行的视图
- php - 如何使用 php 更新 SQLite 表中的数据?
- css - 如何更改 Google Charts 类别过滤器中下拉框的高度
- sql - CASE 表达式总和 - 加入其他表时的问题
- elasticsearch - Elasticsearch 节点崩溃
- oracle - 使同一表中 2 列中的值相互唯一
- php - 如何在php中正确转义数组?