Home > Mobile >  How can I half the array
How can I half the array

Time:12-27

I am learning to code and I am trying out this javascript object method course. I am currently stuck on this method. I want to have the array with three different numbers(10,20,5) to be /2. I do not understand why it is returning NaN. Thank you for reading.

shirtPrice = 10
jeanPrice = 20
shoePrice = 5

shoppingList = [shirtPrice,jeanPrice,shoePrice];

const shoppingDiscountDay = {
  discountedItems: {
    calculateItemsDiscount() {
        return shoppingList/2; //return NaN
    },
  }
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());

CodePudding user response:

Try using .map()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

const shoppingDiscountDay = {
  discountedItems: {
    calculateItemsDiscount() {
        const itemsHalfPrice = shoppingList.map(item=>item/2)
        return itemsHalfPrice;

    },
  }
}

CodePudding user response:

You cannot divide an array, you need to divide each of the elements in it.

You can use the .map method which applies a function on each of the elements of an array and returns a new array with the results

shirtPrice = 10
jeanPrice = 20
shoePrice = 5

shoppingList = [shirtPrice, jeanPrice, shoePrice];

const shoppingDiscountDay = {
  discountedItems: {
    calculateItemsDiscount() {
      return shoppingList.map(itemPrice => itemPrice / 2);
    },
  }
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());

CodePudding user response:

You can't perform '/' operation on array. It is meant to be perform on numbers. Instead try this.

shirtPrice = 10
jeanPrice = 20
shoePrice = 5

shoppingList = [shirtPrice,jeanPrice,shoePrice];

const shoppingDiscountDay = {
  discountedItems: {
    calculateItemsDiscount() {
       for(let i = 0;  i < shoppingList.length; i  ){
          shoppingList[i] = shoppingList[i]/2;  
       }
        return shoppingList; 
    },
  }
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());
  • Related