LoginSignup
2
2

More than 5 years have passed since last update.

JavaScriptでよくやるArray Sort

Posted at

:writing_hand: ramdajs

sample.mjs
import R from "ramda";

const arr = [
  { name: "zzz", age: 20 },
  { name: "bbb", age: 5 },
  { name: "bbb", age: 50 },
  { name: "bbb", age: 32 },
  { name: "vvv", age: 8 }
];

// single key
console.table(R.sort(R.ascend(R.prop("name")), arr));
console.table(R.sort(R.descend(R.prop("name")), arr));

// ↑とやりたいこと的にはだいたい同じ
console.table(R.sortBy(R.prop("name"))(arr));
console.table(R.reverse(R.sortBy(R.prop("name"))(arr)));

// multi key
console.table(
  R.sortWith([R.ascend(R.prop("name")), R.ascend(R.prop("age"))])(arr)
);
console.table(
  R.sortWith([R.descend(R.prop("name")), R.descend(R.prop("age"))])(arr)
);
実行(v10.6.0)
node --experimental-modules sample.mjs

┌─────────┬───────┬─────┐
│ (index) │ name  │ age │
├─────────┼───────┼─────┤
│    0    │ 'bbb' │  5  │
│    1    │ 'bbb' │ 50  │
│    2    │ 'bbb' │ 32  │
│    3    │ 'vvv' │  8  │
│    4    │ 'zzz' │ 20  │
└─────────┴───────┴─────┘
┌─────────┬───────┬─────┐
│ (index) │ name  │ age │
├─────────┼───────┼─────┤
│    0    │ 'zzz' │ 20  │
│    1    │ 'vvv' │  8  │
│    2    │ 'bbb' │  5  │
│    3    │ 'bbb' │ 50  │
│    4    │ 'bbb' │ 32  │
└─────────┴───────┴─────┘
┌─────────┬───────┬─────┐
│ (index) │ name  │ age │
├─────────┼───────┼─────┤
│    0    │ 'bbb' │  5  │
│    1    │ 'bbb' │ 50  │
│    2    │ 'bbb' │ 32  │
│    3    │ 'vvv' │  8  │
│    4    │ 'zzz' │ 20  │
└─────────┴───────┴─────┘
┌─────────┬───────┬─────┐
│ (index) │ name  │ age │
├─────────┼───────┼─────┤
│    0    │ 'zzz' │ 20  │
│    1    │ 'vvv' │  8  │
│    2    │ 'bbb' │ 32  │
│    3    │ 'bbb' │ 50  │
│    4    │ 'bbb' │  5  │
└─────────┴───────┴─────┘
┌─────────┬───────┬─────┐
│ (index) │ name  │ age │
├─────────┼───────┼─────┤
│    0    │ 'bbb' │  5  │
│    1    │ 'bbb' │ 32  │
│    2    │ 'bbb' │ 50  │
│    3    │ 'vvv' │  8  │
│    4    │ 'zzz' │ 20  │
└─────────┴───────┴─────┘
┌─────────┬───────┬─────┐
│ (index) │ name  │ age │
├─────────┼───────┼─────┤
│    0    │ 'zzz' │ 20  │
│    1    │ 'vvv' │  8  │
│    2    │ 'bbb' │ 50  │
│    3    │ 'bbb' │ 32  │
│    4    │ 'bbb' │  5  │
└─────────┴───────┴─────┘

:moyai: 「...ramdajsほんま便利や」

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