1
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?

More than 5 years have passed since last update.

【JavaScript TypeScript】オブジェクトを要素に持つ配列をオブジェクトのキーごとにソート

Posted at

例えば

[{name: "Aさん", age: 42},{name: "Bさん", age: 23},{name: "Cさん", age: 379}]

みたいなデータを

{ name: [ 'Aさん', 'Bさん', 'Cさん' ], age: [ 42, 23, 379 ] }

キーごとにソートしたい!

JavaScript(ES6)

いろんな方法がありますが、reduce使うのがベターかなと思っています。

sortArrayByKey.js

function sortArrayByKey(arr) {
  const object = arr.reduce((prev, current) => {
    Object.keys(current).forEach((key) => {
      if(!prev[key]) prev[key] = []
      prev[key].push(current[key])
    })
    return prev
  },{})
  return object
}

const base = [{name: "Aさん", age: 42},{name: "Bさん", age: 23},{name: "Cさん", age: 379}]
const sorted = sortArrayByKey(base) // { name: [ 'Aさん', 'Bさん', 'Cさん' ], age: [ 42, 23, 379 ] }

TypeScriptでの注意

むしろこちらのほうが重要で、reduceにより型が全く変わる場合の記法を知りませんでした。

sortArrayByKey.ts
interface BaseObj {
  [key: string]: string | number;
}

interface SortedObj {
  [key: string]: (string | number)[] ;
}

function sortArrayByKey(arr: BaseObj[]): SortedObj {
  const object = arr.reduce<SortedObj>((prev, current) => {
    Object.keys(current).forEach((key) => {
      if(!prev[key]) prev[key] = []
      prev[key].push(current[key])
    })
    return prev
  },{})
  return object
}

const base = [{name: "Aさん", age: 42},{name: "Bさん", age: 23},{name: "Cさん", age: 379}]
const sorted = sortArrayByKey(base) // { name: [ 'Aさん', 'Bさん', 'Cさん' ], age: [ 42, 23, 379 ] }

arr.reduce<SortedObj>
ここで返り値の型宣言をしないと、返り値の型がBaseObjインタフェースで認識されてしまい、pushreturn objectでエラーが発生します。

1
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
1
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?