Loop array and compare previous item and next item.
My array:
const array = [{id: 1,name: 'A'},{id: 2,name: 'B'},{id: 3,name: 'B'},{id: 4,name: 'B'},{id: 5,name: 'C'},{id: 6,name: 'D'},{id: 7,name: 'E'},{id: 8,name: 'E'},{id: 9,name: 'E'}]
My Code:
let result = []
array.forEach(function(item, index) {
if (index > 0) {
if (array[index].name == array[index - 1].name) {
result.push(array[index - 1].name)
}
}
});
console.log('result :', result); // result I got [ 'B', 'B', 'E', 'E' ]
But I want this result:
let result = [ 'B', 'B', 'B', 'E', 'E', 'E' ]
2
Answers
You can consider using a temporary group to handle the consecutive items with the same name. Whenever a different name is encountered, check if the temporary group has more than one element. If so, add its contents to the result array. Finally, handle the last group if it has more than one element.
Hope this will help for you.