Skip to main content

Array

🤖WARNING
The English translation was done by AI.

Array Deduplication

// 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]);
}

Array Filling

new Array(10).fill(1);

Array.from({ length: 10 }, item => 1);

Array Flattening

// Array.prototype.flat([depth])
let arr = [1, 2, 7, [2, [2, 3], 6]];

console.log(arr.flat(Infinity));

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
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);