HomeToolsAbout

Array Strategies

Remove empty or falsy elements

const array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,]; // remove empty holes, preserve undefined and null const filtered = array.filter(() => true); // [0, 1, null, 2, '', 3, undefined, 3, 4, 4, 5, 6] // remove falsy values based on Boolean constructor const filtered2 = array.filter(Boolean); // [1, 2, 3, 3, 4, 4, 5, 6]

Finding distinct elements

Distinct primitive elements

const elements = [1, 2, 2, 3, 4, 5, 5, 6]; const distinctElements = [...new Set(elements)]; // [1, 2, 3, 4, 5, 6];

Distinct object entry values

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]

Get First Element of Array

// 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];

Grab Random Index from Array

let randItemFromArray = items[Math.floor(Math.random()*items.length)];
AboutContact