Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

例えば

[{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でエラーが発生します。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away