Array
🤖WARNING
The English translation was done by AI.
Array Deduplication
- Method 1
- Method 2
- Method 3
// Naive method
const arr = [1, 1, 2, 5, 2, 6, 8];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (newArr.includes(arr[i])) {
continue;
}
newArr.push(arr[i]);
}
const arr = [1, 3, 45, 6, 3, 2, 0];
const newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(arr); // [1, 3, 45, 6, 3, 2, 0]
console.log(newArr); // [1, 3, 45, 6, 2, 0]
const arr = [1, 3, 45, 6, 3, 2, 0];
const newArr = [...new Set(arr)];
console.log(arr); // [1, 3, 45, 6, 3, 2, 0]
console.log(newArr); // [1, 3, 45, 6, 2, 0]
Array Filling
new Array(10).fill(1);
Array.from({ length: 10 }, item => 1);
Array Flattening
- Method 1
- Method 2
- Method 3
- Method 4
// Array.prototype.flat([depth])
let arr = [1, 2, 7, [2, [2, 3], 6]];
console.log(arr.flat(Infinity));
// Recursive with for...of
let arr = [1, 2, 7, [2, [2, 3], 6]];
function flat(arr) {
let newArr = [];
for (const item of arr) {
if (Array.isArray(item)) {
newArr = newArr.concat(flat(item));
} else {
newArr.push(item);
}
}
return newArr;
}
console.log(flat(arr));
// Spread operator
const arr = [1, 2, 7, [2, [2, 3], 6]];
function flat(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(flat(arr));
// Clever operation
const arr = [1, 2, 7, [2, [2, 3], 6]];
function flat(arr) {
const result = arr
.toString()
.split(',')
.map(item => {
return +item;
});
return result;
}
console.log(flat(arr));
Finding the Maximum Value in an Array
const arr = [1, 2, 1, 4, 2, 10];
console.log(Math.max.apply(null, arr));
const arr = [1, 2, 1, 4, 2, 10];
console.log(arr.sort((a, b) => a - b)[arr.length - 1]);
const arr = [1, 2, 1, 4, 2, 10];
console.log(Math.max(...arr));
Sorting Character Arrays
const arr1 = ['A1', 'A2', 'B1', 'B2'];
const arr2 = ['A', 'B'];
const c = [...arr1, ...arr2].sort(
(a, b) =>
a.charCodeAt(0) - b.charCodeAt(0) || a.length - b.length || a.charCodeAt(1) - b.charCodeAt(1)
);
// ['A', 'A1', 'A2', 'B', 'B1', 'B2']
Sorting Object Arrays
const users = [
{
name: 'Alan',
age: 19
},
{
name: 'Bob',
age: 25
}
];
const userList = users.sort((a, b) => b.age - a.age);
// Sort based on age, note: sort will modify the original array
Map Related
const a = ['1', '2', '3'].map(parseInt);
// The '1' in array a is converted to decimal.
console.log(a); // [1, NaN, NaN]
// map has three parameters (item, index, array)
/* parseInt(string, radix)
When radix equals 0 or undefined or is not specified, if string starts with '0x' or '0X', then radix is 16
If it starts with '0', radix is 10/8 depending on the actual situation. */
// Breakdown process
parseInt('1', 0);
parseInt('2', 1);
parseInt('3', 2);