How can I create an array with return result of a function?

59 views Asked by At

I created a simple calculator

johnRestBill = [124, 48, 268, 180, 42]; //dollar

function tipCal(){
  for(var i = 0; i < johnRestBill.length; i++){
  if (johnRestBill[i] < 50) {
    console.log(johnRestBill[i] * .2);
  } else if (johnRestBill[i] >= 50 && johnRestBill[i] <= 200){
    console.log(johnRestBill[i] * .15);
  } else {
    console.log(johnRestBill[i] * .1);
  }
 }
}
return tipCal();

I got the result of each index of johnRestBill array and now I want to make an array with the result. So I made var tips = [] and typed tips.push(tipCal()) but it is not working and I don't know why...

2

There are 2 answers

0
CertainPerformance On

To create tips, it would be much more appropriate to use .map instead, and for that, you need a function that returns the calculated tip:

const johnRestBill = [124, 48, 268, 180, 42];

function tipCal(bill) {
  if (bill < 50) return bill * .2;
  else if (bill >= 50 && bill <= 200) return bill * .15;
  else return bill * .1;
}
const tips = johnRestBill.map(tipCal);
console.log(tips);

0
brk On

You can use array map method and return the same logical conditions

var johnRestBill = [124, 48, 268, 180, 42]; //dollar
// map returns a new array 
let arr = johnRestBill.map(function(item) {
  if (item < 50) {
    return item * .2;
  } else if (item >= 50 && item <= 200) {
    return item * .15;
  } else {
    return item * .1;
  }
})
console.log(arr)