-3

I have an associative array, with a number used as key, something like this:

    let array1 = [
    [456, {
        "field1": "value1",
        "field2": "value2",
    }],
    [789, {
        "field1": "value1",
        "field2": "value2",
    }],
    [123, {
        "field1": "value1",
        "field2": "value2",
    }]
];

and then I have another simply array like this:

let array2 = [123, 456, 789];

is there a way to order array1 accordingly to array2?

user3174311
  • 1,714
  • 5
  • 28
  • 66
  • 2
    Have you tried anything? Show your attempt. – axiac Nov 13 '19 at 16:37
  • Use `Array.prototype.map`, call the function on array2 and return the appropriate values from array1 – TKoL Nov 13 '19 at 16:40
  • *"I have an associative array"* -- JavaScript does not provide associative arrays. It provides the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) built-in class but you don't use it. There isn't any associative array (or something with the same functionality) in the code you posted. Just two regular arrays (i.e. indexed with consecutive integral numbers, starting with `0`). – axiac Nov 13 '19 at 16:41
  • Does this answer your question? [Javascript - sort array based on another array](https://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array) – ASDFGerte Nov 13 '19 at 16:42

2 Answers2

1

You can simply use reduce method on array1 and then place elements in result by index of the current element number in array2.

let array2 = [123, 456, 789];
let array1 = [[456,{"field1":"value1","field2":"value2"}],[789,{"field1":"value1","field2":"value2"}],[123,{"field1":"value1","field2":"value2"}]]

const result = array1.reduce((r, [k, v]) => {
  r[array2.indexOf(k)] = [k, v];
  return r;
}, []);

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1
array1.sort((a, b) => array2.indexOf(a[0]) - array2.indexOf(b[0]));

How about this?