Arrays
Table of Contents
- Overview
- Test if an array is empty
- Concatenate arrays
- Convert an array to an object
- Test if an array contains an element
Array.prototype.sort()
Sorting Stability in Different Browsers
Overview
- Prefer JavaScript’s higher-order functions instead of loops like
for-in
orfor-of
. - Use
map()
/every()
/filter()
/find()
/findIndex()
/reduce()
/some()
/ …
Test if an array is empty howto
- Just use
array.length
;
if (typeof array !== 'undefined' && array.length > 0) {
// the array is defined and has at least one element
}
Concatenate arrays howto
- if
arrays
> ~150000, this can fail. In this case you should use a loop-based approach.
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
- Use
Array.prototype.includes()
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:
- IE6+: stable
- Firefox < 3: unstable
- Firefox >= 3: stable
- Chrome <= 5 (i.e., all versions to date): unstable
- Opera < 10: unstable
- Opera >= 10: stable
- Safari 4: stable