Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash - Move object to first place in array?

Tags:

arrays

lodash

I have an array of objects, with type of fruit/vegetable:

For the one type vegetable I have, I want it to be the first item in the array, but I am not sure how to do so with lodash.

var items = [
    {'type': 'fruit', 'name': 'apple'},
    {'type': 'fruit', 'name': 'banana'},
    {'type': 'vegetable', 'name': 'brocolli'}, // how to make this first item
    {'type': 'fruit', 'name': 'cantaloupe'}
];

Here is a fiddle with my attempt: https://jsfiddle.net/zg6js8af/

How can I get type vegetable to be the first item in the array regardless of its current index?

like image 437
Wonka Avatar asked Jun 09 '17 05:06

Wonka


1 Answers

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);
like image 119
SeregPie Avatar answered Sep 23 '22 22:09

SeregPie