DEV Community

loading...

Discussion on: What’s your alternative solution? Challenge #13

Collapse
ctrleffive profile image
Chandu J S

We can use the filter method.

const getPositives = (dataArray) => {
  return dataArray.filter(item => item >= 0)
}

const mixedArray = [-5, 10, -3, 12, -9, 5, 90, 0, 1]
const filteredArray = getPositives(mixedArray)

console.log(filteredArray)
// OUTPUT:  (6) [10, 12, 5, 90, 0, 1]

Or, in a single line,

const mixedArray = [-5, 10, -3, 12, -9, 5, 90, 0, 1]
// no need of a function.
const filteredArray = mixedArray.filter(item => item >= 0)

console.log(filteredArray)
// OUTPUT:  (6) [10, 12, 5, 90, 0, 1]
Forem Open with the Forem app