DEV Community

Andrew
Andrew

Posted on

Корисні JavaScript методи які помістяться в один рядок

1. Вибір випадкового елементу з масиву

// Input: [1, 2, 3, 4]
const randomElement = arr => arr[Math.floor(Math.random() * arr.length)];
// Output: Something like 2, or 4, or 1... you get it.
Enter fullscreen mode Exit fullscreen mode

2. Позбавлення від повторюваних елементів масиву

// Input: [1, 2, 2, 3]
const uniqueArray = [...new Set([1, 2, 2, 3])];
// Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

3. Сортування об'єктів масиву за певною властивістю

// Input: 'name', [{name:'Bob', age:25}, {name:'Alice', age:22}]
const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] || -1);
// Output: [{name:'Alice', age:22}, {name:'Bob', age:25}]
Enter fullscreen mode Exit fullscreen mode

4. Перевірка рівності двох масивів або об'єктів

// Input: [1, 2], [1, 2]
const arraysEqual = JSON.stringify([1, 2]) === JSON.stringify([1, 2]);
// Output: true
Enter fullscreen mode Exit fullscreen mode

5. Зробити так, щоб код чекав певний час

const chill = ms => new Promise(resolve => setTimeout(resolve, ms));

(async () => {
  console.log("Before waiting");
  await chill(2000);
  console.log("After waiting for 2 seconds");
})();
Enter fullscreen mode Exit fullscreen mode

6. Витяг властивості з масиву об'єктів

const pluck = (arr, key) => arr.map(obj => obj[key]);
console.log(pluck([{x: 1}, {x: 2}], 'x')); // Output: [1, 2]
Enter fullscreen mode Exit fullscreen mode

7. Вставка елемента в певну позицію

// Input: [1, 2, 4]
const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem), a);
// Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

8. Згенерувати випадковий HEX код кольору

// Input: No input needed
const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6, 0);
// Output: Something like #f5a623
Enter fullscreen mode Exit fullscreen mode

Top comments (0)