Reputation: 8576
I have an array that looks like this:
var arr = [
{name: 'Price'},
{name: 'Sale'},
{name: 'Shipping'},
{name: 'Customer Rating'}
]
Is there a way to sort this array so that a specific item is at a given index? For example, I always want 'Customer Rating' to be at index 1.
var arr = [
{name: 'Price'},
{name: 'Customer Rating'}
{name: 'Sale'},
{name: 'Shipping'}
]
Bonus points for es6 one liner solutions!
Upvotes: 2
Views: 177
Reputation: 848
What you are looking for is a swap rather than a sort.
Like the answer above, you will need to find the element first.
let i = arr.findIndex(item => item.name === 'Customer Rating');
Then jump over to this answer for the rest.
Javascript swap array elements
Upvotes: 0
Reputation: 8660
Find an object based on a passed in name, remove it, and then add it back in at the specified index. You can do this using splice
let setIndex = (arr, index, namevalue) => {
arr.splice(arr.findIndex( ({name}) => name == namevalue ), 1);
arr.splice(index, 0, {name: namevalue});
return arr;
}
var arr = [
{name: 'Price'},
{name: 'Sale'},
{name: 'Shipping'},
{name: 'Customer Rating'}
]
let setIndex = (arr, index, namevalue) => {
arr.splice(arr.findIndex( ({name}) => name == namevalue ), 1);
arr.splice(index, 0, {name: namevalue});
return arr;
}
arr = setIndex(arr, 0, 'Customer Rating');
console.log(arr);
Upvotes: 0
Reputation: 18378
Using map
and find
:
var arr = [
{name: 'Price'},
{name: 'Sale'},
{name: 'Shipping'},
{name: 'Customer Rating'}
];
var sorted = ['Price', 'Customer Rating', 'Sale', 'Shipping']
.map(e => arr.find(({name}) => name === e));
console.log(sorted);
Upvotes: 0
Reputation: 224859
Find element with name:
let i = arr.findIndex(item => item.name === 'Customer Rating');
Remove item:
let [item] = arr.splice(i, 1);
Insert item:
arr.splice(1, 0, item);
Don’t put this in one line:
arr.splice(1, 0, ...arr.splice(arr.findIndex(x => x.name=='Customer Rating'), 1));
let arr = [
{name: 'Price'},
{name: 'Sale'},
{name: 'Shipping'},
{name: 'Customer Rating'}
];
let i = arr.findIndex(item => item.name === 'Customer Rating');
let [item] = arr.splice(i, 1);
arr.splice(1, 0, item);
console.log(arr);
Upvotes: 3