给出具有以下结构的对象数组(固定长度):
{type: 'A', value: 1}
或
{type: 'B', text: 'b'}
查找“A”类型对象的所有序列并返回其索引的最简单方法是什么?
一个例子: 对于以下数组:
[
{type: 'A', value: 1}, {type: 'A', value: 2}, {type: 'B', text: 'b1'},
{type: 'A', value: 11}, {type: 'A', value: 12}, {type: 'A', value: 13},
{type: 'B', text: 'b2'}, {type: 'A', value: 10}, {type: 'B', text: 'b3'}
]
输出应为以下数组:
[
{startIndex: 0, startValue: 1, length: 2},
{startIndex: 3, startValue: 11, length: 3},
{startIndex: 7, startValue: 10, length: 1},
]
我猜最简单的实现是使用 forEach
进行迭代,并且有许多复杂的条件,但是有没有更简单的技术?
谢谢。
最佳答案
您可以使用 reduce
像这样。添加变量 prev
来跟踪之前的 type
是什么。如果当前类型
是您要查找的类型:如果前一项具有不同的类型
,则添加一个对象。否则,只需增加 length
属性
let input = [{type:'A',value:1},{type:'A',value:2},{type:'B',text:'b1'},{type:'A',value:11},{type:'A',value:12},{type:'A',value:13},{type:'B',text:'b2'},{type:'A',value:10},{type:'B',text:'b3'}],
prev;
const output = input.reduce((acc, { type, value }, i) => {
if (type === 'A') {
if (prev !== type) {
acc.push({ startIndex: i, startValue: value, length: 1 })
} else {
acc[acc.length - 1].length++
}
}
prev = type
return acc;
}, [])
console.log(output)
关于javascript - JS 查找数组中的所有序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233889/