Skip to content Skip to sidebar Skip to footer

Convert Multidimensional Array To One-dimensional Array

I have a multidimensional array. I want to group the values in this and know how many. I've created a new array. I've looped a multidimensional array. If the current value does not

Solution 1:

You could reduce the array by reduceing the inner array and look for the wanted id.

var array = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
    result = array
        .reduce((r, a) => {
            var o = a.reduce((p, id) => {
                var temp = p.subCategories.find(q => q.id === id);
                if (!temp) {
                    p.subCategories.push(temp = { id, subCategories: [] });
                }
                return temp;
            }, r);
            o.count = (o.count || 0) + 1;
            return r;
        }, { subCategories: [] })
        .subCategories;

console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

This is in the same style as you had, by using a starting object which matches the inner format and a search for the items for returning this object for next level.

var currentArray = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
    newArray = [],
    temp,
    item;

for (let i = 0; i < currentArray.length; i++) {
    temp = { subCategories: newArray };
    for (let k = 0; k < currentArray[i].length; k++) {
        item = temp.subCategories.find(x => x.id === currentArray[i][k]);
        if (!item) {
            temp.subCategories.push(item = { id: currentArray[i][k], subCategories: [] });
        }
        temp = item;
    }
    temp.count = (item.count || 0) + 1;
}

console.log(newArray);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Convert Multidimensional Array To One-dimensional Array"