-3

I am using Google's directions API to get an optimized routes list given several points. It returns an array with the right order for the points:

[4, 0, 6, 7, 1, 3, 5, 2]

I want to use that array to order my points as well, which is an array of objects:

[obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7]

And get as a result:

[obj4, obj0, obj6, obj7, obj1, obj3, obj5, obj2]

What can I do in order to accomplish this?

Multitut
  • 2,089
  • 7
  • 39
  • 63

4 Answers4

7

You can use the function map.

var indexes = [4, 0, 6, 7, 1, 3, 5, 2],
    objs = ['obj0', 'obj1', 'obj2', 'obj3', 'obj4', 'obj5', 'obj6', 'obj7'],
    result = indexes.map(i => objs[i]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
0
//googleArray = [4, 0, 6, 7, 1, 3, 5, 2]
var myArray = [];
myOldArray = [obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7];
for(var i in googleArray){
    myArray[i] = myOldArray[googleArray[i]];
}
Tendai
  • 100
  • 8
0

You could iterate through the order array, building up a new array as you go:

var orders = [4, 0, 6, 7, 1, 3, 5, 2];
var objects = [obj0, obj1, obj2, obj3, obj4, obj5, obj6, obj7];

var output = [];
for (var i = 0; i < orders.length; i++) {
    output.push(objects[orders[i]]);
}
Duffy
  • 41
  • 3
0
function orderArr(reference, arrayToOrder) {
    var ordArr = [];
    referenceArr.forEach((e, i) => {
        ordArr.push(arrayToOrder[e])
    })
    return ordArr;
}

You have a lot of options, haha!

But the @Ele answer is the best one.

yajiv
  • 2,901
  • 2
  • 15
  • 25
Gustavo Henrique
  • 138
  • 1
  • 14