0

I'm not good with array and never have been. So this is probably a simple and stupid question but here goes:

I have an array of objects. Each object looks like this :

obj = { color: "blue", name: "Some description", id: 1 }

Currently it is arranged in the following manner:

[Blue, Blue, Beige, Beige, Cyan, Cyan]

What I need to do is to sort this array based on object's color property to looks like this:

[Blue, Beige, Cyan, Blue, Beige, Cyan]

Thanks :)

kernelpanic
  • 2,876
  • 3
  • 34
  • 58

1 Answers1

1

Sorry, firstly I misunderstood the question.

Here is my updated solution:

'use strict';

let _ = require('lodash');

let colors = [
  {color: "Blue", id: 1},
  {color: "Blue", id: 2},
  {color: "Beige", id: 3},
  {color: "Beige", id: 4},
  {color: "Cyan", id: 5},
  {color: "Cyan", id: 6},
];

let sort = function(array) {
    let order = ["Blue", "Beige", "Cyan"];
    let ordered = [];
    let nextColor = 0;

    do {
        let itemIndex = _.findIndex(array, function(item) {
            return item.color == order[nextColor];
        });
        let item = _.pullAt(array, itemIndex);
        ordered.push(item.pop());

        nextColor++;
        if(nextColor == array.length) {
            nextColor = 0;
        }
    } while ( array.length )

    return ordered;
}

colors = sort(colors);

console.log(colors);

/*
Result:
[ { color: 'Blue', id: 1 },
  { color: 'Beige', id: 3 },
  { color: 'Cyan', id: 5 },
  { color: 'Blue', id: 2 },
  { color: 'Beige', id: 4 },
  { color: 'Cyan', id: 6 } ]
*/
Gergo
  • 2,190
  • 22
  • 24