skip to Main Content

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


  1. 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.

    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' }
    ];
    
    let result = [];
    let tempGrp = [];
    
    array.forEach(function (item, index) {
      if (index === 0 || item.name === array[index - 1].name) {
        tempGrp.push(item.name);
      } else {
        if (tempGrp.length > 1) {
          result = result.concat(tempGrp);
        }
        tempGrp = [item.name];
      }
    });
    
    if (tempGrp.length > 1) {
      result = result.concat(tempGrp);
    }
    
    console.log('result:', result);
    Login or Signup to reply.
  2. Hope this will help for you.

    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' }
    ];
    
    const result = [];
    let prevName = null;
    let count = 0;
    
    array.forEach(item => {
      if (item.name === prevName) {
        count++;
      } else {
        if (count > 1) {
          for (let i = 0; i < count; i++) {
            result.push(prevName);
          }
        }
        prevName = item.name;
        count = 1;
      }
    });
    
    if (count > 1) {
      for (let i = 0; i < count; i++) {
        result.push(prevName);
      }
    }
    
    console.log('result:', result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search