JS array methods you should know (part3)
Ok guys, we are here in the last part.
1-concat():
The famous concat()! As you can conclude it returns a
merged array from 2 or more array(s).
The syntax is pretty easy :
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];
const res = letters.concat(numbers);
console.log(res);
as you see the first array come in first then the
second in argument :
(6) ['a', 'b', 'c', 1, 2, 3]
We can do the same for multiple arrays using :
concat(a,b,c…)
Or you can add element !
2-fill():
A method for lazy people .used specially to initialize
arrays to predefined values. It will fill the array with exactly the given
value.
If the array already contains values. it will override
it.
This method will change the array and also return the
modified one.
We can add 2 parameter to indicate the beginning and
the end of filling (the end index won’t be reached)
const nums =[1,55,3,14,8]
const a =new Array(4).fill(0);
const res = nums.fill('*',1,4);
console.log(res)
console.log(a)
and the output :
(5) [1, '*', '*', '*', 8]
(4) [0, 0, 0, 0]
3-includes():
It works like the find() method. But it allows a
flexible search for an element without the need to insert a function.
const nums =[1,55,3,14,8]
const res = nums.includes(3);
console.log(res)
and the result is ‘true’
4-pop() and push():
Those methods change the current array and can return
the new array.
Push to insert an element in the end and pop to delete
a one.
Push can have multiple parameters at once.
This is all
guys , hope you like it
No comments