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.
const arr = ['x', '', '', 'x', '', '', '']; const emptyIndexes = arr.reduce((acc, curr, index) => { if (curr === '') { acc.push(index); } return acc; }, []); console.log(emptyIndexes);
roster = ["x", "", "", "x", "", "", ""] emptyIndexArray = [] for (i = 0; i < roster.length; i++) { if (roster[i] === "") { emptyIndexArray[emptyIndexArray.length] = i; } } emptyIndexArray.forEach(x => console.log(x));
arr.map((item, index) => item === '' ? index : null).filter(item => item)
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]
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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.