Frogtown
Frogtown

Reputation: 49

Count occurring pairs in array - Javascript

I want to find and count the pair of values within an array.

For example:

var Array = ["Apple", "Pear", "Mango", "Strawberry", "Apple", "Pear", "Orange"];

Now I want to count how many times each pair (Apple and Pear, Pear and Mango and so on...) occurs in the array. If the array has uneven pair, the last value should then be zero.

The output of the array in the example should then be:

[2,1,1,1,1]

Notice that the "Apple, Pear" occurs 2 times so then the count will be two and put in the first number of the new array.

I hope I explained good enough

Upvotes: 2

Views: 4201

Answers (3)

WesleyAC
WesleyAC

Reputation: 553

This is the simplest way to do it. It is similar to the answer given by @Nina Scholz above, but without having to join or anything like that. Also note that, while it defaults to pairs (i.e., 2), it is generic enough to check for triples, quadruples, and so on:

function CountMultiples(inputArray, quantity = 2) {
    var count = {};

    return inputArray.reduce((acc, val) => {
            count[val] = (count[val] || 0) + 1;

            return count[val] % quantity > 0 ? acc : ++acc;
        }, 0);
};

var a = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 0, 0, 0, 6];
console.log(CountMultiples(a,4));//0
console.log(CountMultiples(a,3));//1
console.log(CountMultiples(a));//4

Upvotes: 0

Emeeus
Emeeus

Reputation: 5250

You could use sort() taking advantage of the fact that it passes the pairs needed to the callback:

var arr = ["Apple", "Pear", "Mango", "Strawberry", "Apple", "Pear", "Orange"];

var pairs = {}

arr.sort((a,b)=>{
    (a+b in pairs)?pairs[a+b]++:pairs[a+b] = 1;
})

console.log(Object.values(pairs))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could use a hash table for counting pairs by using two adjacent values and build a key of it for counting. Then use the values as result.

var array = ['Apple', 'Pear', 'Mango', 'Strawberry', 'Apple', 'Pear', 'Orange'],
    count = {},
    result;
    
array.reduce((a, b) => {
    var key = [a, b].join('|');
    count[key] = (count[key] || 0) + 1;
    return b;
});

result = Object.values(count);

console.log(result);
console.log(count);

Upvotes: 2

Related Questions