Helpful Javascript array techniques
Javascript array reduce promise pattern
let userIDs = [1,2,3];
userIDs.reduce( async (previousPromise, nextID) => {
await previousPromise;
return methodThatReturnsAPromise(nextID);
}, Promise.resolve());
Ref: https://css-tricks.com/why-using-reduce-to-sequentially-resolve-promises-works/
Looping over a NodeList in Javascript
Using Javascript array
iteration functions to loop over a NodeList
requires some special handling.
The easiest way is to use Array.from()
Array.from(document.querySelectorAll('div'))
.map(div => div.style.border = '1px solid crimson')
Older info from this source:
let divs = document.querySelectorAll('div')
[].forEach.call(divs, function(div) {
// do whatever
div.style.color = "red"
});
Array.prototype.slice
can also now do the conversion:
Array.prototype.slice.call(document.childNodes)
which can be shortened to
[].slice.call(document.childNodes)
See also here for more detail.
Remove duplicates from array in Javascript
arr.filter((val, i, self) => self.indexOf(val) === i)
Javascript equivalent of python range
function
let size = 10, startAt = 1;
[...Array(size).keys()].map(i => i + startAt);
produces
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
or, simply for a range starting at zero
[...Array(9).keys()];
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
See this posting for a more complete discussion.
Flatten an array
let arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
]
let merged = [].concat.apply([], arrays)
console.log(merged);
The posting at https://stackoverflow.com/a/10865042 gives the following explanation:
Using the .apply()
method of .concat()
takes the second param as an array,
so the last line effectively does this:
let merged2 = [].concat(
["$6"], ["$12"], ["$25"], ["$25"],
["$18"], ["$22"], ["$10"]
)
Rotate an array
Forwards:
arr.push(arr.shift())
and in reverse:
arr.unshift(arr.pop())
Intersection of two arrays
let intersect = arr1.filter(e => arr2.includes(e))
Difference of two arrays
let diff = arr1.filter(e => !arr2.includes(e))