How do you push multiple objects into an array?
There are different ways to push the elements into a single array using JavaScript.
- Push()
- Unshift()
- Spread operator
1. Push(): This operator add multiple items in end of an array.
# Lets take an empty array
- let array = [];
#add elements using push operator
- array.push(5);
- array.push(10);
# Print an array using
- console.log(array);
Output: (2) [5,10]
2. Unshift() : To add multiple objects at the start of an array.
- let array = [];
- array.unshift(10);
- array.unshift(5);
- console.log(array);
Output: (2) [5,10]
3. Spread Operator: This operator helps you copy one array into another array.
- let array1 = [1, 2, 3];
- let array2 = ['Hello', ...arr1, 'World'];
- console.log(arr2);
In this operator if you are not use three dot it throw an error.
Comments
Post a Comment