Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 23, 2020 04:06 pm GMT

10 JavaScript Array/Object Tricks

1. Initialize an array of size n and fill with default values

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

2. Insert something in middle of array

const arr = [1, 2, 3, 4];const index = 2;const insertText = "hello";// Solution 1 - Split at the index and rejoin themconst 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 arrayconst 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 addconsole.log(arrCopy); // [ 1, 2, 'hello', 3, 4 ]
Enter fullscreen mode Exit fullscreen mode

3. Pick random element from an array

const themes = ['neo', 'black & white', 'color'];const randomNumber =  Math.round(Math.random() * 100); // random number between 0 - 100const randomElement = randomNumber % themes.length; // so that the number is within the arrays range console.log(themes[randomElement]);
Enter fullscreen mode Exit fullscreen mode

4. Check if a value is an array

const arr = [1, 2, 3];console.log(typeof arr); // objectconsole.log(Array.isArray(arr)); // true
Enter fullscreen mode Exit fullscreen mode

5. Remove duplicates from array

const array = [1, 1, 2, 3, 5, 5, 1];const uniqueArray = [...new Set(array)];console.log(uniqueArray); // [1, 2, 3, 5]
Enter fullscreen mode Exit fullscreen mode

6. Check if an object is empty

const obj = {};console.log(!!obj); // always returns true, even if the object is emptyconst totalKeys = Object.keys(obj).length; // returns the total number of keys in an objectconsole.log(totalKeys ? 'Not Empty' : 'Empty');
Enter fullscreen mode Exit fullscreen mode

7. Check if a property exists in an object

const obj = {  test: undefined};// cannot differentiate if the property is not present or the value is undefinedconsole.log( obj.test ); // undefined// the property existsconsole.log( "test" in obj ); // true
Enter fullscreen mode Exit fullscreen mode

8. Loop over an object

const age = {  john: 20,  max: 43};// Solution 1 - Get 'keys' and loop overconst keys = Object.keys(age);keys.forEach(key => age[key]++);console.log(age); // { john: 21, max: 44 }// Solution 2 - for..in loopfor(let key in age){    age[key]++;}console.log(age); // { john: 22, max: 45 }
Enter fullscreen mode Exit fullscreen mode

9. Prevent an object's properties value from updating

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
Enter fullscreen mode Exit fullscreen mode

10. Object keys are stored in insertion order

const obj = {  name: "Human",  age: 0,  address: "Earth",  profession: "Coder",};console.log(Object.keys(obj)); // name, age, address, profession
Enter fullscreen mode Exit fullscreen mode

Objects maintain the order in which the keys were created.

Thanks for reading

Follow @codedrops.tech for daily posts.

Instagram Twitter Facebook

Micro-Learning Web Development Javascript MERN stack Javascript

codedrops.tech


Original Link: https://dev.to/318097/10-tricks-on-javascript-arrays-and-objects-3pi

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To