简体   繁体   中英

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?

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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM