'Combine two arrays on primary key and foreign key and sort data

I have two arrays like this:

let employees = [
    {
        "id":"1",
        "name" : "John Doe"
    },
    {
        "id":"4",
        "name" : "Peter Jones"
    },
    {
        "id":"3",
        "name" : "Jack Johnson"
    },
    {
        "id":"2",
        "name" : "Ron Morris"
    }
]

let salaries = [
    {
        "employeeId" : "1",
        "salary": "1500"
    },
    {
        "employeeId" : "2",
        "salary": "150"
    },
    {
        "employeeId" : "3",
        "salary": null 
    },
    {
        "employeeId" : "4",
        "salary": "1780"
    }
]

Result should be an exposed function for retrieving employees with their salaries from the server.

Function should support returning employees ascending or descending by salary.

I tried something like this but it does not work:

let result = employees.map(e => ({...e, salary: salaries.filter(({ employeeId }) => employeeId === e.id).sort((a,b) => (a.salary > b.salary) ? 1 : ((b.salary > a.salary) ? -1 : 0))}));

Thanks in advance.



Solution 1:[1]

This addresses the broader requirements of making it a function, allowing for a parameter that determined ascending or descending order, and also where to place null values.

let employees = [
    {
        "id": "1",
        "name": "John Doe"
    },
    {
        "id": "4",
        "name": "Peter Jones"
    },
    {
        "id": "3",
        "name": "Jack Johnson"
    },
    {
        "id": "2",
        "name": "Ron Morris"
    }
];
let salaries = [
    {
        "employeeId": "1",
        "salary": "1500"
    },
    {
        "employeeId": "2",
        "salary": "150"
    },
    {
        "employeeId": "3",
        "salary": null
    },
    {
        "employeeId": "4",
        "salary": "1780"
    }
];

/**
 * @param {boolean} true for ascending, false for descending
 * @param {number} value to use for nulls to determine where to place them
 */
function combineAndSort(employees, salaries, ascending, nullAs = Number.MAX_VALUE) {
    return employees.map((employee) => {
        return {
            ...employee,
            salary: parseInt(salaries.find((salary) => salary.employeeId === employee.id)?.salary)
        };
    }).sort((a, b) => {
        const aVal = isNaN(a.salary) ? nullAs : a.salary;
        const bVal = isNaN(b.salary) ? nullAs : b.salary;
        const diff = aVal - bVal;
        return ascending ? diff : -diff;
    });
}
console.log(combineAndSort(employees, salaries, true));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dave Meehan