Array Functions Flashcards
Create an array from a string.
const someStr = ‘hello world’;
- Array.from(someStr);
- […someStr]
- someStr.split(‘’);
- Object.assign([], string);
Create an array with a function to map every element of the array.
Array.from([1, 2, 3], x => x + 1);
Create array with a number of empty slots
Array(3);
Initialize an array with values
Array.of(1, 2, 3);
const arr = [1, 2, 3];
Array(1, 2, 3);
Get 3rd to last index of an array
const arr = [1, 2, 3, 4, 5, 6];
console.log(arr.at(-3)];
combine 2 arrays. returning new array and without returning new array
const arr1 = [a, b, c]; const arr2 = [1, 2, 3];
arr1.concat(arr2);
[…ar1, …arr2];
[].concat(arr1, arr2);
arr1.push(…arr2);
Fill an array with values
fill(value)
fill(value, start)
fill(value, start, end)
conditional to see if every element of an array passes
[12, 54, 18, 130, 44].every(x => x >= 10); // true
find last element or index of an array given a testing function
array. findLast(…)
array. findLastIndex(…)
const arr2 = [0, 1, 2, [[[3, 4]]]] how to turn that into [0, 1, 2, 3, 4]
how to turn that flat with a function to apply to every element?
with flat
console.log(arr2.flat(2));
with “flatMap”
determine whether the array contains a value.
[1, 2, 3].includes[1];
the last index of an element
[1, 2, 3, 2].lastIndexOf(2)
join all elements of an array to a string. also with a separator character
[1, 2, 3].join(‘-‘);
[1, 2, 3].toString(); // without separator
remove first element of array
[1, 2, 3].shift();
add to front of the array
array1.unshift(4, 5); // also returns length of new array