1

I have an ordered array and 4 arrays inside another array. I want to order each array based on the ordered array.

(this is just an example, I need a code that will work with any kind of elements inside the arrays).

let ordered_array = ['a','b','c','d','e','f','g','h','i','j','k','l'];
  let array = [['d','c','a'],['i','k','b'],['f','e','h'],['l','g','j']];
  //order each array in 'array'
  for(let i = 0; i < array.length; i++){
    for(let l = 0; l < array[i].length; l++){
      document.write(array[i][l]);
    }
    document.write('</br>');
  }
  /*
  expected output (after order):
  acd 
  bik
  efh
  gjl
  */
0

1 Answer 1

0

You could take a Map and sort by the indices.

var ordered_array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
    array = [['d', 'c', 'a'], ['i', 'k', 'b'], ['f', 'e', 'h'], ['l', 'g', 'j']],
    order = ordered_array.reduce((m, v, i) => m.set(v, i), new Map);
    
array.forEach(t => t.sort((a, b) => order.get(a) - order.get(b)));

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

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

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.