Created
October 18, 2020 21:52
-
-
Save Megajjks/f383e0d47d18f2b59914751ec3723324 to your computer and use it in GitHub Desktop.
Ways to itered a data in javascript Interview questions
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
// 1. Demonstrate all the different ways to iterate the below array | |
const myArray = [1, 2, 3, 4, 5, 6]; | |
// 1 method | |
for (let index = 0; index < myArray.length; index++) { | |
console.log(myArray[index]) | |
} | |
// 2 method | |
myArray.forEach((element) => {console.log(myArray[element]);}); | |
// 3 method, not is the best way but pass, but in practice it is only used in objects or arrays that are transformed or mutated | |
const newArray = myArray.map((idx)=>(console.log(idx))); | |
// 2. Demonstrate all the different ways to iterate the keys of | |
// the below object | |
const myObject = { x: 1, y: "hi" }; | |
// 1 method | |
for (const key in myObject) { | |
console.log(key); | |
} | |
// 2 method | |
const keys = Object.keys(myObject); | |
console.log(keys) | |
// 3 method | |
for (const [key, value] of Object.entries(myObject)) { | |
console.log(key); | |
} | |
// 4 method | |
Object.entries(myObject).forEach(([key, value]) => { | |
console.log(key); | |
}); | |
// 3. Repeat #2, demonstrate different ways to iterate | |
// the values of "myObject" | |
// 1 method | |
const obj = myObject.map((item) => console.log(`x:${item.x} y:${item.y}`)); | |
// 2 method | |
for (const key in myObject) { | |
console.log(`${key}: ${myObject[key]}`); | |
} | |
// 3 method | |
Object.values(myObject).forEach((val) => console.log(val)); | |
// 4 method | |
for (const [key, value] of Object.entries(myObject)) { | |
console.log(`${key}: ${value}`); | |
} | |
// 5 method | |
Object.entries(myObject).forEach(([key, value]) => { | |
console.log(`${key}: ${value}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment