[ JavaScript ] 連想配列を複数の要素で並び替える

例えば objects をid,年齢の昇順に並び替える実装を Vanilla JavaScript で行なった場合は以下のようになります。

const objects = [
    {id: 1, name: 'foo', age: 22},
    {id: 3, name: 'foobar', age: 20},
    {id: 2, name: 'foobar', age: 24},
    {id: 2, name: 'foobar', age: 30},
    {id: 2, name: 'bar', age: 20},
];

const compareId = (a, b) => {
    if (a.id > b.id) {
        return 1;
    } else if (a.id === b.id) {
        return 0;
    } else {
        return -1;
    }
};
const compareAge = (a, b) => {
    if (a.age > b.age) {
        return 1;
    } else if (a.age === b.age) {
        return 0;
    } else {
        return -1;
    }
};


const compare = (funcs, a, b) => {
    for (let func of compareFuncs) {
        if (func(a, b) === 1) {
            return 1;
        } else if (func(a, b) === -1) {
            return -1;
        }
    }
    return 0;
};


const wrappedCompare = (funcs, a, b) => {
    return compare(funcs, a, b)
};

const compareFuncs = [compareId, compareAge];
const sortedObjects = objects.sort(wrappedCompare.bind(this, compareFuncs));
console.log(sortedObjects);

出力結果は以下

[ { id: 1, name: 'foo', age: 22 },
  { id: 2, name: 'bar', age: 20 },
  { id: 2, name: 'foobar', age: 24 },
  { id: 2, name: 'foobar', age: 30 },
  { id: 3, name: 'foobar', age: 20 } ]

ちなみに lodash の _.sortBy 関数を使うともっと簡潔に書くことができます。

const _ = require('lodash');

const objects = [
    {id: 1, name: 'foo', age: 22},
    {id: 3, name: 'foobar', age: 20},
    {id: 2, name: 'foobar', age: 24},
    {id: 2, name: 'foobar', age: 30},
    {id: 2, name: 'bar', age: 20},
];


const compareAge = (obj) => {
    return obj.age;
};

const compareId = (obj) => {
    return obj.id;
};


const sortedObjects = _.sortBy(objects, [compareId, compareAge]);
console.log(sortedObjects);

Related Contents

Pickup Contents