Created
December 26, 2019 21:52
-
-
Save iamsonal/f3e6b32341b7bbfaae6c274a8be050b3 to your computer and use it in GitHub Desktop.
Array.from() and Array.of()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Array.from() will take something aray-ish and convert it into an array | |
| // *** Example 1: If we have DOM like below | |
| { | |
| /* <div class="people"> | |
| <p>John</p> | |
| <p>Kait</p> | |
| <p>Snickers</p> | |
| </div> */ | |
| } | |
| const people = document.querySelectorAll(".people p"); // Type is Nodelist | |
| const peopleArray = Array.from(people); // to convert nodelist into an array | |
| const names = peopleArray.map(person => person.textContent); // ['John', 'Kait', 'Snickers'] | |
| // The above example can be done in a different way. Array.from() take a 2nd argument which | |
| // is a map function which will allow us to modify data as we are creating the array | |
| const people2 = document.querySelectorAll(".people p"); | |
| const peopleArray2 = Array.from(people2, person => { | |
| console.log(person); | |
| return person.textContent; | |
| }); | |
| console.log(peopleArray2); | |
| // *** Example 2: Converting arguments object into an array | |
| function sumAll() { | |
| const nums = Array.from(arguments); | |
| return nums.reduce((prev, next) => prev + next, 0); | |
| } | |
| sumAll(2, 34, 23, 234, 234, 234234, 234234, 2342); | |
| ////////////////////////////////////////////////////////////////////////////// | |
| // Array.of() will create an array from every single argument passed | |
| const ages = Array.of(12, 4, 23, 62, 34); | |
| console.log(ages); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment