Amit Dhamu

Software Engineer

Sort Array of Objects by Property

const sortArrayOfObjectsByProperty = (array, property, direction = 'asc') => {
    const operators = {
        '>': (a, b) => a > b,
        '<': (a, b) => a < b,
    };

    let operator = operators['>'];
    direction = direction.toLowerCase();

    if (direction === 'desc') {
        operator = operators['<'];
    }

    return array.sort((a, b) => {
        if (operator(a[property], b[property])) {
            return 1;
        }
        if (operator(b[property], a[property])) {
            return -1;
        }
        return 0;
    });
};

 array / object / sort / es6 / arrow function

Valid PHP TypesWrite to a File in Node

Show Comments

Made with by Amit Dhamu.
© MMXX. All rights reserved.