'Order segment of array by property [duplicate]
Can u help me please create a function which change order part of array by property.
Example:
const input = [
{firstName: 'Jack1', lastName: 'Snow1'},
{firstName: 'Jack2', lastName: 'Snow2'},
{firstName: 'Jack3', lastName: 'Snow3'},
{firstName: 'Jack4', lastName: 'Snow4'},
{firstName: 'Jack5', lastName: 'Snow5'},
];
const order = ['Jack3', 'Jack2', 'Jack4'];
function orderBySegment(input, order, 'firstName') {
}
const output = [
{firstName: 'Jack3', lastName: 'Snow3'},
{firstName: 'Jack2', lastName: 'Snow2'},
{firstName: 'Jack4', lastName: 'Snow4'},
{firstName: 'Jack1', lastName: 'Snow1'},
{firstName: 'Jack5', lastName: 'Snow5'},
];
Solution 1:[1]
const input = [
{firstName: 'Jack1', lastName: 'Snow1'},
{firstName: 'Jack2', lastName: 'Snow2'},
{firstName: 'Jack3', lastName: 'Snow3'},
{firstName: 'Jack4', lastName: 'Snow4'},
{firstName: 'Jack5', lastName: 'Snow5'},
];
const order = ['Jack3', 'Jack2', 'Jack4'];
function orderBySegment(input, order, key) {
return input.sort((a, b) => {
const aValue = a[key], bValue = b[key];
const aIndex = order.indexOf(aValue), bIndex = order.indexOf(bValue);
if (aIndex === -1)
return 1;
else if (bIndex === -1)
return -1;
else
return aIndex - bIndex;
});
}
console.log(orderBySegment(input, order, 'firstName'));
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 | Amir MB |
