lodash - Move object to first place in array?
you can do it with ordering by type
in desc
direction:
var res = _.orderBy(items, ['type'], ['desc']);
or using partition
var res = _.chain(items)
.partition({type: 'vegetable'})
.flatten()
.value();
Why use lodash when you do not need it (and can write functional code using a single reduce
) ?
var items = [
{'type': 'fruit', 'name': 'apple'},
{'type': 'fruit', 'name': 'banana'},
{'type': 'vegetable', 'name': 'brocolli'},
{'type': 'fruit', 'name': 'cantaloupe'}
];
var final = items.reduce(function(arr,v) {
if (v.type === 'vegetable') return [v].concat(arr)
arr.push(v)
return arr
},[]);
alert(JSON.stringify(final));
Using lodash _.sortBy. If the type is vegetable, it will be sorted first, otherwise second.
let items = [
{type: 'fruit', name: 'apple'},
{type: 'fruit', name: 'banana'},
{type: 'vegetable', name: 'brocolli'},
{type: 'fruit', name: 'cantaloupe'},
];
let sortedItems = _.sortBy(items, ({type}) => type === 'vegetable' ? 0 : 1);
console.log(sortedItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Here is another solution without using lodash.
function sortBy(array, fn) {
return array.map(v => [fn(v), v]).sort(([a], [b]) => a - b).map(v => v[1]);
}
let items = [
{type: 'fruit', name: 'apple'},
{type: 'fruit', name: 'banana'},
{type: 'vegetable', name: 'brocolli'},
{type: 'fruit', name: 'cantaloupe'},
];
let sortedItems = sortBy(items, ({type}) => type === 'vegetable' ? 0 : 1);
console.log(sortedItems);