I'm trying to discover a more concise way of finding the indexes in an array that match a condition and then push them into an array. I've made some attempts but either doesn't return the answer I want or are much too verbose.
Could someone shed some ES6 light here as to what the best way of doing this is? thanks for any help
var arr = ["00", "000", "", "0", "000"],
p = [];
var l = (arr.reduce((a, b) => a.length > b.length ? a : b)).length;
arr.filter(c => c.length === l); // returns ["000", "000"]
arr.map(c => c.length === l); // returns [false, true, false, false, true]
arr.map((c, i) => c.length === l ? i : c); // returns ["00", 1, "", "0", 4]
// arr.findIndex(return c.length === l) // error
function longestInstances(el) {
return el.length == l
} // returns 1 only (after console logged)
console.log(arr.findIndex(longestInstances));
for (i = 0; i < arr.length; i++) {
// works but verbose
if (arr[i].length == l) {
p.push(i);
}
console.log('p: ' + p);
}
Array.prototype.findis probably what you're looking for.