10 трюков с массивами/обьектами в JavaScript

10 трюков с массивами/обьектами в JavaScript

Debian-Lab

1. Инициализируем массив размера n и заполненяем его значениями по умолчанию

const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]


2. Вставляем что-нибудь в середину массива

const arr = [1, 2, 3, 4];
const index = 2;
const insertText = "hello";

// Solution 1 - Split at the index and rejoin them
const result = [...arr.slice(0, index), insertText, ...arr.slice(index)];
console.log(result); // [1, 2, 'hello', 3, 4]

// Solution 2 - .splice() - It can be used to add/remove elements from array
const arrCopy = [...arr]; // splice modified the array on which the operation is performed.
arrCopy.splice(index, 0, insertText); // arguments are - index, no of elements to remove, new element to add
console.log(arrCopy); // [ 1, 2, 'hello', 3, 4 ]


3. Выбираем случайный элемент из массива

const themes = ['neo', 'black & white', 'color'];

const randomNumber =  Math.round(Math.random() * 100); // random number between 0 - 100
const randomElement = randomNumber % themes.length; // so that the number is within the arrays range 
console.log(themes[randomElement]);


4. Проверяем, является ли значение массивом

const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true


5. Удаляем дубликаты из массива

const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // [1, 2, 3, 5]


6. Проверяем, пуст ли объект

const obj = {};
console.log(!!obj); // always returns true, even if the object is empty

const totalKeys = Object.keys(obj).length; // returns the total number of keys in an object
console.log(totalKeys ? 'Not Empty' : 'Empty');

7. Проверяем, существует ли свойство в объекте

const obj = {
  test: undefined
};

// cannot differentiate if the property is not present or the value is undefined
console.log( obj.test ); // undefined

// the property exists
console.log( "test" in obj ); // true

8. Loop над объектом

const age = {
  john: 20,
  max: 43
};

// Solution 1 - Get 'keys' and loop over
const keys = Object.keys(age);
keys.forEach(key => age[key]++);

console.log(age); // { john: 21, max: 44 }

// Solution 2 - for..in loop
for(let key in age){
    age[key]++;
}

console.log(age); // { john: 22, max: 45 }


9. Запрещаем обновление значения свойств объекта

const obj = {name: 'Codedrops'};
console.log(obj.name); // Codedrops

/* Set the 'writable' descriptor to false for the 'name' key  */
Object.defineProperty(obj, 'name', {
        writable: false
});

obj.name = 'ABC';
console.log(obj.name); // Codedrops


10. Делаем так, чтобы ключи объектов хранились в порядке вставки

const obj = {
  name: "Human",
  age: 0,
  address: "Earth",
  profession: "Coder",
};

console.log(Object.keys(obj)); // name, age, address, profession

⏳ Наш основной канал - @debian_lab

🌆 Наш канал с приватными сливами - @slivkins_lab

Report Page