-1

I have an array that could be made up of any the following values:

input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];

'input' can be made of any # of these values, without any duplicates. I'm trying to figure out how to sort 'input' according to the order of 'sortingArray':

sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];

Any help would be greatly appreciated.

0

4 Answers 4

3

You can also use filter function and get copy of sortingArray including only values from input:

var input = ['S-1','S-2','S-3','S-4','S-5'];
var sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];

var result = sortingArray.filter((el)=>(input.indexOf(el) > -1));
console.log(JSON.stringify(result));

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

5 Comments

This would not work. The results would essentially be a copy of the input array.
You can run this snippet and see output: ["S-1","S-5","S-2","S-3","S-4"]
@Pointy, look at the snippet output...
maybe the question is wrong worded, or this answer. i see a semantic difference between sorted and filtered result. the answer does only work if from each element in input only zero or one element of sortingArray exists.
@NinaScholz OP wrote: "'input' can be made of any # of these values, without any duplicates."
2

Build a look-up object from your "sorting array":

var indexes = sortingArray.reduce(function(lookup, key, index) {
  lookup[key] = index;
  return lookup;
}, {});

Now you can use that in a comparator function:

input.sort(function(k1, k2) {
  return indexes[k1] - indexes[k2];
});

Comments

1

Simple use with for loop.And apply the if condition for half of the array length.Then pass with new array

var input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
var c =eval(input.length/2);
arr=[];
for(var i=0; i<input.length; i++){
  if(i < c)
    {
      arr.push(input[i]);
      arr.push(input[i+c]);
      }
       }
console.log(arr)

Comments

0

You could use an object with the indices of the sorted array and sort the new array with it.

var input = ['S-1', 'S-2', 'S-3', 'S-4', 'S-5', 'S-6', 'S-7', 'S-8'],
    sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"],
    order = Object.create(null);

sortingArray.forEach(function (a, i) { order[a] = i; });
input.sort(function (a, b) { return order[a] - order[b]; });

console.log(input);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.