James Oshomah James Oshomah - 21 days ago 5
Javascript Question

Grouping array values

I have an already sorted array. Assuming my sorted array is

[60 , 60 ,60, 56 , 56 ,45 , 33 , 12, 10]


I want to place this array in an object of this form using javascript

{first : [60 ,60 ,60] , second : [56 ,56] , third : [33]}


Please any help will be appreciated. THanks

Answer

You could use a nested approach with two loops, one for the wanted keys and one for the length of the array with the numbers.

var numbers = [60, 60, 60, 56, 56, 45, 33, 12, 10],
    object = {},
    i = 0; j = 0,
    keys = ['first', 'second', 'third'],
    last = numbers[0];

while (i < keys.length) {
    object[keys[i]] = object[keys[i]] || [];
    while (j < numbers.length && numbers[j] === last) {
        object[keys[i]].push(numbers[j]);
        j++;
    }
    last = numbers[j];
    i++;
}

console.log(object);

A proposal with more compact style.

var numbers = [60, 60, 60, 56, 56, 45, 33, 12, 10],
    object = {};

['first', 'second', 'third'].forEach(function (last) {
    var j = 0;

    return function (k) {
        object[k] = object[k] || [];
        while (j < numbers.length && numbers[j] === last) {
            object[k].push(numbers[j]);
            j++;
        }
        last = numbers[j];
    };
}(numbers[0]));

console.log(object);