how to copy array
simple way
1 | const sheeps = ['π', 'π', 'π']; |
built-in way
The Array.from()
method creates a new, shallow-copied Array
instance from an array-like or iterable object.
1 | console.log(Array.from('foo')); |
Why Canβt I Use =
to Copy an Array?
Because arrays in JS are reference values, so when you try to copy it using the =
it will only copy the reference to the original array and not the value of the array.
To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.
1 | const sheeps = ['π', 'π', 'π']; |
how to copy array part
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
1 | var animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; |
how to modify array
how to sort Array
Array.sort()
1 | var months = ['March', 'Jan', 'Feb', 'Dec']; |
Be able to custom sorting for Array
1 | function compare(a, b) { |
Example:
1 | var numbers = [4, 2, 5, 1, 3]; |
Be able to filter Array elements
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
1 | var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; |
Several method how to iterate Array elements
Basic For Loop
Lodash forEach
The
forEach()
method executes a provided function once for each array element.The
map()
method creates a new array with the results of calling a provided function on every element in the calling array.The
entries()
method returns a new Array Iterator object that contains the key/value pairs for each index in the array.