Home > Blockchain >  To use modern array methods to generate 2 dimensional array
To use modern array methods to generate 2 dimensional array

Time:12-12

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

You could reduce the array and look for undefined or a falsy value like '' and push a new array to the result set.

const
    list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""],
    result = list.reduce((r, v, i, a) => {
        if (!a[i - 1]) r.push([]);
        if (v) r.at(-1).push(v);
        return r;
    }, []);

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

CodePudding user response:

const list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""];
var result_array = [];
var tmp_list = [];
list.forEach( item => {
    if( item === "" ) { result_array.push( tmp_list ); tmp_list = []; }
    else tmp_list.push( item );
});

console.log( result_array );

@Nina Scholz is more elegant -- this seems more readable to me, though.

CodePudding user response:

const list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""];

let a = [...list], r = []
while(a.length) r.push(a.splice(0,1 a.indexOf('')).slice(0,-1))

console.log(r)

CodePudding user response:

console.log(
  String(
    ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""]
  //["", "1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""]
  )
  .split(',,')
  .map(str => 
    str
      .replace(/^,|,$/, '')
      .split(',')
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

Convert it to a string, .split it, then .map it to a function making a new array with each .split item.

var list = ["1", "2", "3", "", "4", "5", "6", "", "7", "8", "9", ""];
console.log(list.toString().split(",,").map(x => x.split(",").filter(y => y.length > 0)));

  • Related