const elements = [1, 2, 2, 3, 4, 5, 5, 6]; const distinctElements = [...new Set(elements)]; // [1, 2, 3, 4, 5, 6];
Callback can be passed into the
const objectArr = [ {"name": "John", "age": 17}, {"name": "Anny", "age": 24}, {"name": "Paul", "age": 24}, ]; const distinctObjectValues = [ ...new Set(objectArr.map(x => x.age)) ]; // [17, 24]
// The simplest way to access the first element array[0]
But this requires you to check if array[0]
exists
The advantage of find()
is its efficiency as it exits the loop when the first value satisfying the condition is reached
const first = array.find(Boolean) // first element even if falsy const first = array.find(() => true) // can be falsy, but not null or undefined const first = array.find(e => typeof e !== 'undefined')
Using destructuring
const [first] = [1,2,3];
let randItemFromArray = items[Math.floor(Math.random()*items.length)];