Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce JS array length if next elements equal previous

I'd like to combine identical elements in an array, into a single term with how many times the value appears

function combineArrayElements(arr) {
  return arr.map((e, i, ar) => {
    if (e === ar[i + 1] || (e[0] && e[0] === ar[i + 1])) {
      return [e, e[1] + 1]
    }
    return e;
  })
}

Some example input and output:

// input  [3, 2, 2, 5, 1, 1, 7, 1]
// output [3,[2,2],5,[1,2],7,1]

// input  [1, 1, 1, 2, 1]
// output [[1,3], 2, 1]
like image 996
Alex Latro Avatar asked Aug 02 '26 21:08

Alex Latro


1 Answers

You could reduce the array and if the value is equal the last value, take an array and increment the counter.

const
    getGrouped = array => array.reduce((r, v, i, { [i - 1]: last }) => {
        if (v === last) {
            if (!Array.isArray(r[r.length - 1])) r[r.length - 1] = [r[r.length - 1], 1];
            r[r.length - 1][1]++;
        } else {
            r.push(v);
        }
        return r;
    }, []);

console.log(getGrouped([3, 2, 2, 5, 1, 1, 1, 7, 1]));
console.log(getGrouped([2, 2, 2, 3]));
like image 198
Nina Scholz Avatar answered Aug 05 '26 11:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!