我需要使用Java脚本从对象数组中获取相同键/值对的第一个和最后一个索引。我在下面解释输入数据。
const array= [
{id:"1", name:"A"},
{id:"2", name:"A"},
{id:"3", name:"A"},
{id:"4", name:"B"},
{id:"5", name:"B"},
{id:"6", name:"C"},
{id:"7", name:"C"},
{id:"8", name:"C"},
{id:"9", name:"A"}
{id:"10", name:"A"}
{id:"11", name:"D"}
];
在这里,我有一些对象数组,并且其中存在一些重复的数据。我只需要提取保守地存在的重复数据的第一个索引和最后一个索引,但是对于单个记录,我不需要计算索引。因此,根据要求,我的预期输出应如下所示。
const output = [
{"start":0,"end":2},///for A
{"start":3,"end":4},// For B
{"start":5,"end":7},// For C
{"start":8,"end":9},// Again For A
]
所以在这里,我需要计算保守地存在的每个对象的重复键值对的索引。
答案 0 :(得分:1)
使用reduce
解决您的问题:
const array= [
{id:"1", name:"A"},
{id:"2", name:"A"},
{id:"3", name:"A"},
{id:"4", name:"B"},
{id:"5", name:"B"},
{id:"6", name:"C"},
{id:"7", name:"C"},
{id:"8", name:"C"},
{id:"9", name:"A"},
{id:"10", name:"A"},
{id:"11", name:"D"}
];
const output = array.reduce((acc, item, key) => {
if (key > 0 && array[key-1].name === item.name) {
if (acc.length && acc[acc.length-1].end === key-1) {
acc[acc.length-1].end = key;
} else {
acc.push({start: key-1, end: key});
}
}
return acc;
}, []);
console.log(output);