Tính tổng mảng: sử dụng reduce

const arr = [1, 2, 3, 4, 5, 6];

const sum = arr.reduce((total, value) => total + value, 0);
console.log(sum); // 21

Kiểm tra mảng có phần tử đạt yêu cầu: sử dụng some

const arr = [3, 9, 7, 6];

// thằng nào thi < 5 trượt 
const idiot = arr.some(num => num < 5);
console.log(idiot); // output: true // có thằng trượt :D

Kiểm tra các phần tử trong mảng có đạt yêu cầu: sử dụng every

const arr = [1, 2, 3, 4, 5, 6];

// check tất cả có > 4 không
const greaterFour = arr.every(num => num > 4);
console.log(greaterFour); // output: false sai rồi

// vậy thì nhỏ hơn 10 
const lessTen = arr.every(num => num < 10);
console.log(lessTen); // output: true đúng vl

Sắp xếp phần tử: sử dụng sort

const arr = [1, 2, 3, 4, 5, 6];
const alpha = ['e', 'a', 'c', 'u', 'y'];

// sắp xếp theo thứ tự giảm dần
descOrder = arr.sort((a, b) => a > b ? -1 : 1);
console.log(descOrder); // output: [6, 5, 4, 3, 2, 1]

// sắp xếp theo thứ tự tăng dần
ascOrder = alpha.sort((a, b) => a > b ? 1 : -1);
console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y']

Lấy phần tử cuối cùng trong mảng: sử dụng at

const fruits = ['orange', 'apple', 'banana', 'grape'];

const item = fruits.at(1);
item; // => 'apple'
const item = fruits.at(999);
item; // => undefined
const lastItem = fruits.at(-1);
lastItem; // => 'grape'

Leave a Reply

Your email address will not be published. Required fields are marked *