0
0

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 3 years have passed since last update.

【Javascript】Object内のパラメータを元にArrayをソートする方法

Last updated at Posted at 2019-12-10

Object内のパラメータを元にArrayをソートする方法

orderを元に、昇降順でObjectを並び替える方法を紹介します。

exampleArray
const brothers = [
  {
    name: '次郎',
    order: 2
  },
  {
    name: '太郎',
    order: 1
  },
  {
    name: '三郎',
    order: 3
  }
]

MDNのsort()メソッドのドキュメントでは、引数内functionについて以下のように書いてあります。

function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}

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

実際にやってみようと思います。

## 昇順

```js:昇順.js
console.log(brothers.sort((a, b) => {
  if (a.order > b.order) return 1
  if (a.order < b.order) return -1
  return 0
}))

> Array [Object { name: "太郎", order: 1 }, Object { name: "次郎", order: 2 }, Object { name: "三郎", order: 3 }]

降順

降順.js
console.log(brothers.sort((a, b) => {
  if (a.order > b.order) return -1
  if (a.order < b.order) return 1
  return 0
}))

> Array [Object { name: "三郎", order: 3 }, Object { name: "次郎", order: 2 }, Object { name: "太郎", order: 1 }]

うまくできました。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?