Skip to content

Instantly share code, notes, and snippets.

@yaltha
Last active January 13, 2021 11:34
Show Gist options
  • Save yaltha/a538bce5061f403e2dcf2cd96c82fddb to your computer and use it in GitHub Desktop.
Save yaltha/a538bce5061f403e2dcf2cd96c82fddb to your computer and use it in GitHub Desktop.
Some ways to loop one or more arrays in JS
//given an array
const prices = [12, 50, 223, 59, 30]
//1. FOR , the old shcool way
for (let i = 0 ; i < prices.lenght ; i++) {
//process here
console.log(prices[i]);
}
//2. WHILE
let index = 0;
while (index < prices.length){
console.log(prices[index]);
index++;
}
//3. forEach()
prices.forEach(function(value,index,array){
console.log(`at index ${index} in the array ${array}, the value is ${value}`)
}
//return undefined, bcs no way to stop or break the loop other than throwing an exception
//above code still can show the result
//4. map()
const discount = .2;
const discPrices = prices.map(price => (price * discount).toFixed(2));
console.log(prices); //[ 12, 50, 223, 59, 30 ]
console.log(discPrices);//[ '2.40', '10.00', '44.60', '11.80', '6.00' ]
//5.REDUCE()
//reduce method calculate the value of elemement in the array in to a single value
const totalPrice = prices.reduce((a,b)=> a + b , 0).toFixed(2);
console.log(totalPrice) //374.00
//6.Filter
//uses to filter out some data in the array or object
const prices = [12, 50, 223, 59, 30];
const even = prices.filter(price => price % 2 === 0);
console.log(even); //[ 12, 50, 30 ]
//7. Every
//uses to check all of the element of an array pass a certain condition
//true/false
const prices = [12, 50, 223, 59, 30];
const above50 = prices.every(price => price > 50);
const print = above50 ? 'Yes, every element pass' : 'Not all element passed';
console.log(print); //Not all element passed
///8. Some()
//uses to check at least one of the element of an array pass a certain condition
//true/false
const prices = [12, 50, 223, 59, 30];
const below50 = prices.some(price => price < 50);
const print = below50 ? 'Yes, every element pass' : 'Not all element passed';
console.log(print); //Yes, every element pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment