Arrays

Table of Contents

Overview

Test if an array is empty howto

if (typeof array !== 'undefined' && array.length > 0) {
  // the array is defined and has at least one element
}

Concatenate arrays howto

[].concat(...arrays);

Convert an array to an object howto

function arrayToObject(arr, fk, fv) {
  return arr.reduce((obj, x) => {
    const obj1 = obj; // avoid modifying 'obj' parameter.
    obj1[fk(x)] = fv(x);
    return obj1;
  }, {});
}

Test if an array contains an element howto

let pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
console.log(pets.includes('at'));
true
false

Array.prototype.sort() Sorting Stability in Different Browsers discussion

Some cursory results: