# How to count neighboring numbers in an array using Javascript?

You'll need to keep track of the last number iterated over in a persistent variable, as well as the number of occurrences of the last number which gets incremented:

const arr = [7, 7, 7, 7, 4, 4, 5, 5, 5, 1, 9, 2, 7, 7];
let lastNum = arr[0];
let count = 0;
const results = [];
const doPush = () => {
results.push(
count === 1
? lastNum
: ${lastNum}:${count}
);
};
for (const num of arr) {
if (num !== lastNum) {
doPush();
lastNum = num;
count = 1;
} else count++;
}
doPush();

console.log(results);

var test = [7, 7, 7, 7, 4, 4, 5, 5, 5, 1, 9, 2, 7, 7];

console.log(
test.reduce((acc, element) => {
if (acc.length && acc[acc.length - 1].key == element) {
acc[acc.length - 1].count++;
} else {
acc.push({ key: element, count: 1 });
}

return acc;
}, []).map(element => ${element.key}:${element.count})
);

So the logic first reduces the number to an array, tracking the last key and count. So long as the key is the same, the count is incremented. Once the key changes, a new object is pushed to start the next run. After the reduce is done, a map is performed to convert the key and counts into the desired strings.