4

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

0

7 Answers 7

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

@coloraddict ... Having a late look into this thread again it somehow cheers me up that despite the question ... "To use modern array methods to generate 2 dimensional array" ... the accepted answer is almost the only one which uses additional variables in the outer scope due to an outer while based approach (thus not processing list directly by an array method like shown with Nina's or zer00ne's reduce).
1

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

Comments

1
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.

Comments

1

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)

Comments

1

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

Comments

1

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

3 Comments

Each subarray contains a string, rather than 3 elements
Hehe now your last subarray has an empty string in it...
@AndrewParks thank you! It's gone now. I'm thinking if I could add about 50 lines of code to my answer it might get an upvote here ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.