I'm curious as to why the else if statements in the filter method do not return anything:
var moveZeros = function (arr) {
const nonZeros = arr.filter(value => {
if (value !== 0) return value
else if (typeof value === 'boolean') return value
else if (typeof value === 'object') return value
})
const zeros = arr.toString().match(/0/g).map(Number)
const newArr = nonZeros.concat(zeros)
return newArr
}
Additionally, I would also like to know why I get a similar effect when I try to filter out zeros from an array:
const zeros = arr.filter(value => {
if (value === 0) return value
})
Here is a sample array to test the function:
[ 0, 1, null, 2, false, 1, 0 ]
Thank you for any help!
You don't need to return value in the filter
method, return the boolean which should be true if the value should be selected, like so:
var moveZeros = function (arr) { // also when you use !== 0, you don't need to check the type as it compares type const nonZeros = arr.filter(value => value !== 0) const zeros = arr.filter(value => value === 0) const newArr = nonZeros.concat(zeros) return newArr } console.log(moveZeros([ 0, 1, null, 2, false, 1, 0 ]));
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.