Skip to content

Commit 08d2336

Browse files
committed
02 Arrays Part 2 JS
In this lesson I've learned about merging 2, 3 or multiple arrays, spreading arrays into an single array, converting string, objects e.t.c into an array.
1 parent 0614f84 commit 08d2336

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

02_Basics/02_arrays.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// 2. Arrays
2+
3+
// (i) Methods to merge Arrays,
4+
const marvel_heros = ["Thor", "Hulk", "Loki"]
5+
const dc_heros = ["Flash", "Superman", "Batman"]
6+
// marvel_heros.push(dc_heros)
7+
console.log(marvel_heros); // Output: [ 'Thor', 'Hulk', 'Loki', [ 'Flash', 'Superman', 'Batman' ] ]
8+
/* Note: In this dc_heros array has been taken as an 4th element in marvel_heros array.
9+
And this is not a good practice or a good syntax. */
10+
11+
const all_heros = marvel_heros.concat(dc_heros)
12+
console.log(all_heros); // Output: [ 'Thor', 'Hulk', 'Loki', 'Flash', 'Superman', 'Batman' ]
13+
// Note: .push pushes on existing array & .concat returns a new array.
14+
15+
const all_new_heros = [...marvel_heros, ...dc_heros]
16+
console.log(all_new_heros); // Output: [ 'Thor', 'Hulk', 'Loki', 'Flash', 'Superman', 'Batman' ]
17+
/* Note: This methods is used more, cause we can add multiple values in this ([..., ..., ...]).
18+
19+
----------------------------------------------------------------------------------------------------*/
20+
21+
const another_array = [1, 2, 3, [4, 5], 3, 4, [9, [4, 3]]]
22+
const another_new_array = another_array.flat(Infinity)
23+
console.log(another_new_array); // Output: [1, 2, 3, 4, 5, 3, 4, 9, 4, 3]
24+
/* Note: All the values spreaded into a Array.
25+
26+
----------------------------------------------------------------------------------------------------
27+
28+
(ii) Converting into Array, */
29+
console.log(Array.isArray("Ayush")); // Output: false | Ayush is not an Array.
30+
// Converting it into an Array,
31+
console.log(Array.from("Ayush")); // Output: [ 'A', 'y', 'u', 's', 'h' ] | Converted string into Array.
32+
// Objects into Array,
33+
console.log(Array.from({name: "Ayush"})); // Output: [] | Returns an empty array.
34+
35+
const score1 = 100
36+
const score2 = 200
37+
const score3 = 300
38+
console.log(Array.of(score1, score2, score3)); // Output: [ 100, 200, 300 ]

0 commit comments

Comments
 (0)