2

I have an array of arrays. Some of the arrays contain only a single empty string. I'd like to remove all of those from the parent array.

Before

[[ '*Order Number','*Line Number','*Item Number'],
[ '' ],
[ '018622','2','had-99']]

After

[[ '*Order Number','*Line Number','*Item Number'],
[ '018622','2','had-99']]
2
  • What if the array: ["abcd", "", "ijkl"]? Should it be removed? Commented Apr 28, 2017 at 19:56
  • No, just the example above. Thanks. Commented Apr 28, 2017 at 20:10

3 Answers 3

3

You could use built in Array#filter for it.

var array = [[ '*Order Number','*Line Number','*Item Number'], [''], [ '018622','2','had-99']];

console.log(array.filter(function (a) { return a.toString(); }));

Version which mutates the original array.

var array = [[ '*Order Number','*Line Number','*Item Number'], [''], [ '018622','2','had-99']],
    i = array.length;

while (i--) {
    array[i].toString() || array.splice(i, 1);
}

console.log(array);

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

2 Comments

This works! It's ok that it returns a new array, a simple var order_array = array.filter(function (a) { return a.toString(); }); assigns it to what I need.
With arrow functions is just pure awesomeness array.filter(a => a + '');. +1!
0

I'd probably check both that the array only has length 1 and that the item is an empty string

var list = [[ '*Order Number','*Line Number','*Item Number'], [''], [ '018622','2','had-99']];

list.filter(function(arr){
  if(arr.length === 1 && arr[0] === '') {
    return false;
  }
  return true;
}}

Comments

0

Better approach would be using Array#splice, which deletes specified elements from the parent array.

var arr = [[ '*Order Number','*Line Number','*Item Number'], [''], [ '018622','2','had-99']];

for (var i = 0; i < arr.length; i++) {
  if (arr[i][0] == '' && arr[i].length == 1) {
    arr.splice(i, 1);
    --i;
  }
}

console.log(arr);

Comments

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.