Home > front end >  Find list of empty indices in a javascript array
Find list of empty indices in a javascript array

Time:02-10

Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

["x", "", "", "x", "", "", ""]

Would return something like:

[1,2,4,5,6]

I have attempted something like this:

empty = roster.findIndex((obj) => Object.keys(obj).length === 0)

However I can't come up with a way to iterate over the list.

CodePudding user response:

const arr = ['x', '', '', 'x', '', '', ''];
const emptyIndexes = arr.reduce((acc, curr, index) => {
  if (curr === '') {
    acc.push(index);
  }
  return acc;
}
  , []);
console.log(emptyIndexes);

CodePudding user response:

roster = ["x", "", "", "x", "", "", ""]

emptyIndexArray = []

for (i = 0; i < roster.length; i  ) {
  if (roster[i] === "") {
    emptyIndexArray[emptyIndexArray.length] = i;
  }
}

emptyIndexArray.forEach(x => console.log(x));

CodePudding user response:

Well here is another approach based on character codes.

const removeSpaceDuplicates = (arr) => {
  var result = []

  for(let i = 0; i < arr.length; i  ){
    var x = "x".charCodeAt(0),
        empty = isNaN(arr[i].charCodeAt(0)),
        cur =  arr[i].charCodeAt(0)
    
    if( cur == empty || cur != x){
      result.push(i)
    }
  }
  
  return result
}



//====>  [1, 2, 4, 5, 6]

CodePudding user response:

You can use map() and filter().

const arr = ['x', '', '', 'x', '', '', ''];

const result = arr
  .map((item, index) => (item !== 'x' ? index : ''))
  .filter((item) => item);

console.log(result);

Read more: map(), filter()

CodePudding user response:

arr.map((item, index) => item === '' ? index : null).filter(item => item)

CodePudding user response:

It's not going to be length == 0 right, you want empty or doesn't contain x Also find index returns the first index that match, you have to do a map.

See this solution here: EcmaScript6 findIndex method, can it return multiple values?

Recap:

let roster = ["x", "", "", "x", "", "", ""];
let indexes = ages.map((elm, idx) => (elm == '' || elm != 'x') ? idx : '').filter(String);
console.log( indexes );
  •  Tags:  
  • Related