Edgardo Minotauro
Edgardo Minotauro

Reputation: 77

Concatenate arrays inside array by length

I have an array that looks like this:

[ ["01", "Bolognesa", "51"]
, ["01", "Spaghetti", "52"]
, ["01", "Ricardo", "1", "Manjar", "203", "La", "Beriso"]
, ["03", "Miguel", "4", "Manjar", "22", "El", "Beriso"]
]

I want to merge them inside the array by length. Like this:

[
, [["01", "Bolognesa", "51"],["01", "Spaghetti", "52"]]
, [["01", "Ricardo", "1", "Manjar", "203", "La", "Beriso"],["03", "Miguel", "4", "Manjar", "22", "El", "Beriso"]]
]

I tried mapping and filtering:

   console.log(mappedText.map(i => i.filter(j => j.length)));

but I just can´t crack it. Any ideas?

Upvotes: 0

Views: 57

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

You could take an array and the length as index for grouping and filter the array with boolean.

var array = [["01", "Bolognesa", "51"], ["01", "Spaghetti", "52"], ["01", "Ricardo", "1", "Manjar", "203", "La", "Beriso"], ["03", "Miguel", "4", "Manjar", "22", "El", "Beriso"]],
    result = array
        .reduce((r, a) => {
            r[a.length] = r[a.length] || [];
            r[a.length].push(a);
            return r;
        }, [])
        .filter(Boolean);

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

Upvotes: 1

Related Questions