0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

「reduce関数を使ってオブジェクト配列の中身をマージする」のもっと簡単な方法

Last updated at Posted at 2024-07-17

前の記事

結論

reduceメソッド/groupByメソッドを使ってもっと簡単になる
type Order = {
  name: string;     // 商品名
  price: number;    // 値段
  quantity: number; // 個数
}

const orders: Order[] = [
  { name: 'トマト', price: 100, quantity: 1 },
  { name: 'トマト', price: 100, quantity: 2 },
  { name: 'マンゴー', price: 200, quantity: 1 },
  { name: 'イチゴ', price: 250, quantity: 3 }
];

const reduceSameProductsKai = (orders: Order[]) => {
  return Object.values(
    Object.groupBy(orders, ({name}) => name)
  )
  .map( e => (e as Order[]).reduce(
    (acc, e) => 
      ({...acc, quantity: acc.quantity + e.quantity})
    )
  )
}

console.log(reduceSameProductsKai(orders));
結果
[{
   "name": "トマト",
   "price": 100,
   "quantity": 3
 },
 {
   "name": "マンゴー",
   "price": 200,
   "quantity": 1
 },
 {
   "name": "イチゴ",
   "price": 250,
   "quantity": 3
}] 

この方法だと、indexが隣同士でない同じ種類のデータもマージできます。

トマトのindexがバラバラ
const orders: Order[] = [
  { name: 'トマト', price: 100, quantity: 2 },
  { name: 'マンゴー', price: 200, quantity: 1 },
  { name: 'トマト', price: 100, quantity: 2 },
  { name: 'トマト', price: 100, quantity: 3 },
  { name: 'イチゴ', price: 250, quantity: 3 },
  { name: 'トマト', price: 100, quantity: 1 },
];
結果
[{
  "name": "トマト",
  "price": 100,
  "quantity": 8
}, {
  "name": "マンゴー",
  "price": 200,
  "quantity": 1
}, {
  "name": "イチゴ",
  "price": 250,
  "quantity": 3
}] 

groupByなんていう超便利なインターフェースが実装されているとは知らなかった。
@ttatsfさん、教えてくださり、ありがとうございました!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?