How to filter out an array in such a way that the empty indexes should trigger a new array and the result becomes a two dimensional array. Tried with Vanilla JavaScript and it works, looking for a solution using modern array methods.
var list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""];
Vanilla JavaScript eg:-
var tmp_list = [];
for(let i=0; i<list.length; i++) {
if(list[i].length > 0) {
tmp_list.push(list[i]);
} else {
result_array.push(tmp_list);
tmp_list = [];
}
}
for eg:-
Array indexes with values should be consolidated into an array which is then pushed to the result array
Expected result
var result_array = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]];
Details are commented in example
const list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""];
const result = list.reduce((sub, cur, idx, arr) => {
/*
If current value is a "" AND current index is NOT the last index
add an empty array at the end of array "sub"
*/
if (cur === "" && idx !== arr.length - 1) {
sub.push([]);
/*
Otherwise if current value is "truthy" (not a "")
add current value to the last sub-array of "sub"
*/
} else if (cur) {
sub[sub.length - 1].push(cur);
}
return sub;
}, [[]]);// Initial "sub" is an empty array of arrays
console.log(result);
Hope it helps:
var list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""];
const result = [];
let spaceIndex = list.indexOf("");
while(spaceIndex !== -1) {
result.push(list.slice(0, spaceIndex));
list = list.slice(spaceIndex + 1);
spaceIndex = list.indexOf("");
}
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With