CodeStalker
CodeStalker

Reputation: 23

How to map two arrays with different lengths? (Javascript)

So, I have two arrays containing prices. One is a base price and others are for additives

    const fees = [{
         price: 5,
         title: "normal tarif"
    }, {
         price: 2.5,
         title: "coupon"
    }];

    const extras = [{
      price: 2.00,
      title: "Extra natchos"
    }, {
      price: 2.00,
      title: "Extra sauce"
    }, {
      price: 3.00,
      title: "Extra spicy"
    }];

    const combinedArray = fees.map((x, i) => [x.price, x.price + extras[i].price]);
    
    console.log(combinedArray);

Now, I need to remap them into a new Array which would add their prices together, however, the current code I have for it only goes as far as the number of elements in the first array.

How can I make it so that it will map all elements from the second array aswell?

Upvotes: 2

Views: 1577

Answers (2)

user5734311
user5734311

Reputation:

To combine the two arrays into one, you need more operations. Here's example code:

const fees = [{
  price: 5,
  title: "normal tarif"
}, {
  price: 2.5,
  title: "coupon"
}];

const extras = [{
  price: 2.00,
  title: "Extra natchos"
}, {
  price: 2.00,
  title: "Extra sauce"
}, {
  price: 3.00,
  title: "Extra spicy"
}];

const combinedArray = [].concat(...fees.map(fee => extras.map(extra => fee.price + extra.price)));

console.log(combinedArray);

The inner part creates a two-dimensional array by mapping each fee to an array of fee and extra, the [].concat(...array2D) part converts it into a one-dimensional array.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386736

You could add all prices of the given arrays and return a new array with the sum of each array.

var fees = [{ price: 5, title: "normal tarif" }, { price: 2.5, title: "coupon" }],
    extras = [{ price: 2.00, title: "Extra natchos" }, { price: 2.00, title: "Extra sauce" }, { price: 3.00, title: "Extra spicy" }],
    prices = [fees, extras]
        .map(a => a
            .map(({ price }) => price)
            .reduce((a, b) => a + b, 0));
 
console.log(prices);

Upvotes: 4

Related Questions