Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count neighboring numbers in an array using Javascript?

My input is an array like so:

[7, 7, 7, 7, 4, 4, 5, 5, 5, 1, 9, 2, 7, 7]

I want to group together the numbers and add them, but by neighbors, not by total in the array. So the output would be:

['7:4', '4:2', '5:3', 1, 9, 2, '7:2']

I've attempted a few different methods using reduce, and gotten close but using the built-in Javascript methods I end up counting ALL in the array, not by neighbors.

const firstArray = [7, 7, 7, 7, 4, 4, 5, 5, 5, 1, 9, 2, 7, 7];
const masterArray = [];

const unique = new Set (numberArray); // Set {7, 4, 5, 1, 9, 2, 7}
unique.forEach(u => {
  masterArray.push(numberArray.filter(e => e === u));
});

console.log(masterArray);

Set is obviously wrong to use here because that gets the unique values and counts them, but I want to do it by neighbor only. So then I think I should be using a reduce but I run into the same problem.

like image 670
stonerose036 Avatar asked Dec 03 '20 18:12

stonerose036


People also ask

How do you count the number of occurrences of a number in an array in JavaScript?

To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .

How do you count elements in an array?

Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

Is there a count function in JavaScript?

js | count() Function. The count() function is used to count the number of collections in the element. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.


1 Answers

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.

like image 83
Taplar Avatar answered Sep 20 '22 20:09

Taplar