An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
September 16, 2022 10:02 am GMT
Original Link: https://dev.to/jolamemushaj/three-ways-to-iterate-an-array-340j
Three ways to iterate an array
Given an array of integers, return a new array with each value doubled.
For example: [2, 4, 6] --> [4, 8, 12]
Number #1: We use a for loop to iterate over the elements, transform each individual one, and push the results into a new array.
function doubleValues(array) { let result = []; for (let i = 0; i < array.length; i++) { result.push(array[i] * 2); } return result;}console.log(doubleValues([1, 2, 3, 4]));// [2, 4, 6, 8]
Number #2: For-of loop.
function doubleValues(array) { let result = []; for (const element of array) { result.push(element * 2); } return result;}console.log(doubleValues([1, 2, 3, 4]));// [2, 4, 6, 8]
Number #3: JavaScript Array type provides the map() method that allows you to transform the array elements in a cleaner way.
const array = [1, 2, 3, 4];const doubleValues = array.map(element => element * 2);console.log(doubleValues);// [2, 4, 6, 8]
Original Link: https://dev.to/jolamemushaj/three-ways-to-iterate-an-array-340j
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To