0

I am trying to sort an object comparing with an array. So the loop will look for specific values on the array, until it finds one, and put those 3 elements at the beginning and the rest at the end. I am unsure what is the best way to do this any ideas?

It is something like that:

var arr = [1, 3, 2,4,5,6, 2]; 
var arrSimilar = [1,2,5]


var testSortBy = _.sortBy(arr, function(arrSimilar){    
  // [1,2,5,3,4,6,2]   
});

console.log(testSortBy); // [1,2,5,3,4,6,2]
4
  • Where are two 2s included as elements at resulting array? Commented Sep 18, 2017 at 7:38
  • yes they can be repited Commented Sep 18, 2017 at 7:45
  • Why are there not two 5s at expected result? Commented Sep 18, 2017 at 7:54
  • Somebody change my question... there are suppose to be two 2 Commented Sep 18, 2017 at 10:01

2 Answers 2

1

You could use sorting with map and take the index of the value of similar array as priority sorting and then take the index of all other values as order.

Important is to delete a used value of the similar array, because it is now in use and has no meaning for further similar values. That means, same values are sorted to their original relative index.

var array = [1, 3, 2, 4, 5, 6, 2],
    similar = [1, 2, 5],
    result = array
        .map(function (a, i) {
            var priority = similar.indexOf(a);
            delete similar[priority]; // delete value, but keep the index of other items
            return { index: i, priority: (priority + 1) || Infinity };
        })
        .sort(function (a, b) {
            return a.priority - b.priority || a.index - b.index;
        })
        .map(function (o) {
            return array[o.index];
        });

console.log(result); // [1, 2, 5, 3, 4, 6, 2]

Sign up to request clarification or add additional context in comments.

2 Comments

interesting I am going to try
this makes more sense than anything I will try!... Thank you!
0

You can do that in the following way

  1. Suppose A[] is the original array and B is the priority Array
  2. The answer would be (B intersection A) concat (A-B)

var arr = [1, 3, 2,4,5,6]; 
var arrSimilar = [1,2,5];

let bInterA = arrSimilar.filter((e) => arr.indexOf(e) != -1);

let aDiffb = arr.filter((e) => arrSimilar.indexOf(e) == -1);

console.log(bInterA.concat(aDiffb));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.