There are several very basic tips about Javascript arrays that will help you improve your Javascript skills. Now let's do a little coding...
1.Reverse an Array
let name = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Carl']
reversed = [...name].reverse()]
console.log(reversed)
['Carl', 'Jenny', 'Adam', 'Nancy', 'Matt', 'Mike']
2.Sort Array
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
uniq = [...new Set(names)];
console.log(uniq)
['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Carl']
//method 2
let uniqueArray = names.filter(function(item, pos) {
return names.indexOf(item) == pos;
})
console.log(uniqueArray)
['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Carl']
3.Get random value
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
//Method 2
let a =[ { firstName: 'John', age: 27 }, { firstName: 'Ana', age: 25 }, { firstName: 'Zion', age: 30 } ];
a.sort((a, b) => {
return a.age - b.age;
});
4.Intersection,Union,Difference of two arrays
arrA=[1,3,4,5]
arrB=[1,2,5,6,7]
let intersection = arrA.filter(x => arrB.includes(x));
console.log(intersection)
[1, 5]
Union
let union = [new Set([...arrA, ...arrB])]
console.log(Array.from(union[0]));
[1, 3, 4, 5, 2, 6, 7]
Difference
let difference = arrA.filter(x => !arrB.includes(x));
console.log(difference);
[3, 4]
5.Merge Arrays
let fruits = ['banana','mango','apple']
let veggies = ['tomato','potato','onion']
let food = [...fruits,...veggies]
console.log(food)
['banana', 'mango', 'apple', 'tomato', 'potato', 'onion']
6.Fill array with data
var newArray = new Array(10).fill('data');
console.log(newArray)
['data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data']
//Method 2
var newArray = Array.from(Array(10), () => 0 );
console.log(filledArray)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7.Empty an array
food =['banana', 'mango', 'apple', 'tomato', 'potato', 'onion']
//Method 1
food.length=0
//Method 2
food = [];
//Method 3
while (food.length) { food.pop(); }
console.log(food)
[]
8.Get random value
var items = [25, 45, 21, 65, 43];
v=items[Math.floor(Math.random()*items.length)];
console.log(v)
9.Convert array to an object
var arr = ["One", "Two", 3];
var obj = {...arr};
console.log(obj);
{0: 'One', 1: 'Two', 2: 3}
//second way
Object.assign({}, ['a','b','c']);
console.log(obj);
{0: 'a', 1: 'b', 2: 'c'}
Top comments (0)