Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To use modern array methods to generate 2 dimensional array

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"]];

like image 787
coloraddict Avatar asked Sep 20 '25 12:09

coloraddict


2 Answers

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);
like image 55
zer00ne Avatar answered Sep 23 '25 04:09

zer00ne


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);
like image 41
Amirhossein Avatar answered Sep 23 '25 04:09

Amirhossein