7. Convert to array
Sometimes we have to convert some other data structures, such as sets or strings, into arrays.
Class array: function parameters, dom collection
Array.prototype.slice.call(arguments);Array.prototype.concat.apply([], arguments);
character string:
console.log('string'.split('')); // ["s", "t", "r", "i", "n", "g"]console.log(Array.from('string')); // ["s", "t", "r", "i", "n", "g"]
Set:
console.log(Array.from(new Set(1,2,3))); // [1,2,3]console.log([...(new Set(1,2,3))]); // [1,2,3]
8. Traversal array
There are many ways to traverse arrays, including the bottom layer and high-order functional expressions. Let's introduce several:
for:
const arr = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // 1 2 3
for-in:
const arr = [1, 2, 3]; for (let i in arr) { if(arr.hasOwnProperty(i)) { console.log(arr[i]); }} // 1 2 3
for-of:
const arr = [1, 2, 3]; for (let i of arr) { console.log(i); } // 1 2 3
forEach:
[1, 2, 3].forEach(i => console.log(i))// 1 2 3
while:
const arr = [1,2,3];let i = -1;const length = arr.length;while(++i < length) { console.log(arr[i])}// 1 2 3
Iterative auxiliary statements: break and continue
-
break statement is a statement that jumps out of the current loop and executes after the current loop
-
The continue statement terminates the current loop and continues to execute the next loop
In the above methods, except that forEach does not support jumping out of the loop body, others are supported. Higher order functions are similar to forEach.
Performance comparison:
while > for > for-of > forEach > for-in
If you are writing some libraries or traversing a large amount of data, it is recommended to use while. The famous tool library lodash is full of while. In normal operation, for of or forEach has fully met the requirements.
The following describes several advanced functions. If the condition is true, immediately terminate the loop, otherwise continue to traverse the whole array:
// ES5[1, 2, 3].some((i) => i == 1);// ES6[1, 2, 3].find((i) => i == 1);[1, 2, 3].findIndex((i) => i == 1);
Other high-order functional methods, such as forEach map filter reduce reduceRight every sort, traverse the entire array.
9. Flattened multidimensional array
This function is not very commonly used, but it is sometimes used:
2D array:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];const arr2 = [].concat.apply([], arr1);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
3D array:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = [].concat.apply([], arr1);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, [1, 2, 3], [4, 5, 6], [7, 8, 9]]
concat. The apply method can only flatten two-dimensional arrays, and recursive operations are required when there are many.
function flatten(arr) { return arr.reduce((flat, toFlatten) => { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []);}const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = flatten(arr1);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ES6+(ES2019) provides us with a flat method:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];const arr2 = arr1.flat();console.log(arr2); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The default is to flatten the two-dimensional array. If you want to flatten the multi-dimensional array, it accepts a parameter , depth. If you want to expand the infinite depth, use , Infinity:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = arr1.flat(Infinity);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
There is another way to flatten the two-dimensional array:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = arr1.toString().split(',').map(n => parseInt(n, 10));console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10. Array addition
How do I add elements from an array?
We can use push to add elements from the end of the array, unshift to add elements from the beginning, or splice to add elements from the middle. The concat method creates a new array with the required items, which is a more advanced method of adding elements.
Add elements from the end of the array:
const arr = [1, 2, 3, 4, 5, 6];arr.push(7)console.log( arr ); // [1, 2, 3, 4, 5, 6, 7]
Add elements from the beginning of the array:
const arr = [1, 2, 3, 4, 5, 6];arr.unshift(0)console.log( arr ); // [0, 1, 2, 3, 4, 5, 6]
The working principle of push method is very similar to that of unshift method. All methods have no parameters and return the length attribute of array update. It modifies the array that calls it.
To add an array element using splice:
You only need to set the second parameter of , splice , to , 0 , and there are more instructions on deleting splice , in the array
const arr = [1, 2, 3, 4, 5];arr.splice(1, 0, 10)console.log(arr); // [1, 10, 2, 3, 4, 5]
Add array elements using concat:
const arr1 = [1, 2, 3, 4, 5];const arr2 = arr1.concat(6);console.log(arr2); // [1, 2, 3, 4, 5, 6]
11. Array deletion
Arrays allow us to group values and traverse them. We can add and delete array elements in different ways. Unfortunately, there is no simple array Remove method.
So, how to delete elements from an array?
In addition to the delete method, JavaScript arrays also provide a variety of methods to clear array values.
We can use pop to remove elements from the end of the array, shift to remove elements from the beginning, or splice to remove elements from the middle.
The filter method creates a new array with the required items, which is a more advanced method of deleting unwanted elements.
Remove elements from the end of the array:
You can remove array elements from the end of the array by setting the length property to be less than the current array length. Any element whose index is greater than or equal to the new length will be deleted.
const arr = [1, 2, 3, 4, 5, 6];arr.length = 4; console.log( arr ); // [1, 2, 3, 4]
The pop method deletes the last element of the array, returns the element, and updates the length attribute. The pop method modifies the array that calls it, which means that unlike using delete, the last element is completely deleted and the array length is reduced.
const arr = [1, 2, 3, 4, 5, 6];arr.pop(); console.log( arr ); // [1, 2, 3, 4, 5]
Remove elements from the beginning of the array:
The shift method works very similar to the pop method, except that it deletes the first element of the array instead of the last element.
const arr = [1, 2, 3, 4, 5, 6];arr.shift(); console.log( arr ); // [2, 3, 4, 5, 6]
Both the shift and pop methods have no parameters. They return the deleted elements, update the index of the remaining elements, and update the length attribute. It modifies the array that calls it. If there are no elements or the array length is 0, the method returns undefined.
Delete array elements using splice:
The splice method can be used to add, replace, or delete elements from an array.
The splice method receives at least three parameters:
-
start: the position in the array where the deletion of elements begins
-
deleteCount: how many elements are deleted (optional)
-
items...: Add element (optional)
splice can be added, replaced or deleted.
Delete:
If the deleteCount is greater than the total number of elements after start, all elements after start will be deleted (including the start bit).
If deleteCount is omitted, or its value is greater than or equal to array Length - start (that is, if it is greater than or equal to the number of all elements after start), all elements of the array after start will be deleted.
If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added.
const arr1 = [1, 2, 3, 4, 5];arr1.splice(1); console.log(arr1); // [1];const arr2 = [1, 2, 3, 4, 5];arr2.splice(1, 2) console.log(arr2); // [1, 4, 5]const arr3 = [1, 2, 3, 4, 5];arr3.splice(1, 1) console.log(arr3); // [1,3, 4, 5]
add to:
To add, you only need to set deleteCount to 0, and items is the element to be added.
const arr = [1, 2, 3, 4, 5];arr.splice(1, 0, 10)console.log(arr); // [1, 10, 2, 3, 4, 5]
Replace:
To add, you only need to set the deleteCount to be the same as the number of items. Items is the element to be added.
const arr = [1, 2, 3, 4, 5];arr.splice(1, 1, 10)console.log(arr); // [1, 10, 3, 4, 5]
Note: the splice method actually returns two arrays, the original array (now missing the deleted elements) and the array containing only the deleted elements. If you iterate through elements or multiple identical elements, it's best to use reverse traversal.
To delete a single array element using delete:
Using the delete operator does not affect the length attribute. It also does not affect the index of subsequent array elements. The array becomes sparse, which means that the deleted items are not deleted, but become undefined in a strange way.
const arr = [1, 2, 3, 4, 5];delete arr[1]console.log(arr); // [1, empty, 3, 4, 5]
In fact, the reason why elements are not deleted from the array is that the delete operator is more about freeing memory than deleting elements. Memory is freed when there are no more references to the value.
Use the array filter method to delete matching elements:
Unlike the splice method, filter creates a new array.
filter receives a callback method, and the callback returns true or false. The element that returns true is added to the new filtered array.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];const filtered = arr.filter((value, index, arr) => value > 5);console.log(filtered); // [6, 7, 8, 9]console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Clear or reset array:
The simplest and fastest technique is to set the array variable to an empty array
let arr = [1,2,3];arr = [];
A simple trick to clear an array is to set its length property to 0.
let arr = [1,2,3];arr.length = 0;
Use the splice method without passing the second parameter. This will return a copy of the original element, which may be convenient for some of our scenarios. It is also an array copy method and skill.
let arr = [1,2,3];arr.splice(0);
Using a while loop is not a common way to clear arrays, but it is effective and readable. Some performance tests also show that this is the fastest technology.
const arr = [1, 2, 3, 4, 5, 6];while (arr.length) { arr.pop(); }console.log(arr); // []
12. Other methods
Eliminate false values:
[1, false, '', NaN, 0, [], {}, '123'].filter(Boolean) // [1, [], {}, '123']
Is there a true value:
[1, false, '', NaN, 0, [], {}, '123'].some(Boolean) // true
Are all true values:
[1, false, '', NaN, 0, [], {}, '123'].every(Boolean) // false
Zero filling:
Array(6).join('0'); // '00000' note: if you want to make up five zeros, write 6 instead of 5. Array(5).fill('0').join('') // '00000'
Array maximum and minimum values:
Math.max.apply(null, [1, 2, 3, 4, 5]) // 5Math.min.apply(null, [1, 2, 3, 4, 5]) // 1
Determine palindrome string:
const str1 = 'string';const str2 = str1.split('').reverse().join('');console.log(str1 === str2); // false
Array emulation queue:
Queue first in first out:
const arr = [1];// Join the team arr.push(2); console.log('queued element: ', arr [arr.length - 1])// 2 / / outgoing console Log ('outgoing element: ', arr.shift())// one
Get the last element of the array:
As we usually do:
const arr = [1, 2, 3, 4, 5];console.log(arr[arr.length - 1]); // 5
It's troublesome, but ES has a proposal, which can be obtained through arr[-1] this way in the future. Python also has this coquettish operation:
At present, we can use the Proxy object of ES6 to realize:
const arr1 = [1, 2, 3, 4, 5];function createNegativeArrayProxy(array) { if (!Array.isArray(array)) { throw new TypeError('Expected an array'); } return new Proxy(array, { get: (target, prop, receiver) => { prop = +prop; return Reflect.get(target, prop < 0 ? target.length + prop : prop, receiver);; } })}const arr2 = createNegativeArrayProxy(arr1);console.log(arr1[-1]) // undefinedconsole.log(arr1[-2]) // undefinedconsole.log(arr2[-1]) // 5console.log(arr2[-2]) // 4
Note: Although this method is interesting, it will cause performance problems. Under 500000 cycles, the execution time of Proxy array is about 50 times that of normal array in Chrome browser and 20 times that in Firefox browser. In case of a large number of cycles, please use it with caution. Whether you are interviewing or studying, you should master the usage of Proxy.
End of this article~