Three ways to merge arrays in JavaScript

Learn different ways to merge array in JavaScript Image by Makarios Tang 1. Using for loop We can loop through the array source array which need to be pushed , then add elements one by one function push(fromArray, toArray) { for(let i = 0, len = fromArray.length; i < len; i++) { toArray.push(fromArray[i]); } return toArray;} var array1 …

Remove duplicate values of the array in Javascript.

Learn how to remove the duplicate values in the array Simple Way is using Set (which only contains unique value). var array = [1,2,3,4,1,2,3]; var unique = [… new Set(array)] ; //or var unique = Array.from (new Set(array) ); Another way is var elements = [1,2,3,4,1,2,3]; var uniqueArray = elements.filter(function(element, currentIndex) { return elements.indexOf(element) == …

Getting a random item from an array

Let’s write a function to return a random element from an array. We can use Math.random() to generate a number between 0–1(inclusive of 0, but not 1) randomly. Then multiply the random number with the length of the array. floor to result to make it whole number . That’s it we find the random Index. Let’s …

Design a site like this with WordPress.com
Get started