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]
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With