Iain Freestone

❓ JavaScript Q & A No. 4 - How do I select certain values from an array based on custom logic?

May 31, 2020

Use case

Take an array of numbers and return only the odd values

Answser

const numbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const isOdd = (num) => num % 2;

// Plain JavaScript
console.log(numbersArray.filter(isOdd));

// Ramda
console.log(R.filter(isOdd, numbersArray));

//Lodash
console.log(_.filter(numbersArray, isOdd));

// Result
// [ 1, 3, 5, 7, 9 ]

Reference

Methods used

JavaScript - Array.prototype.filter

Ramda - filter

Lodash - filter