0

Suppose I generate two arrays One that holds Array of numbers:

[5.65, 3.25, 4.34, 6.78]

And another array that holds objects with some information in them

[car.object1, car.object2, car.object3, car.object4]

And the objects in second array are related to the numbers in first array. So object1 is related to 5.65, object2 to 3.25 and so on.

So I want to sort the array 1 in an ascending order and at the same time sort the array 2 also.

So the result should be:

[3.25, 4.34, 5.65, 6.78]

&

[car.object2, car.object3, car.object1, car.object4]

My Approach: (You can just ignore the below answer as I think it is wrong. It does not work.)

var all = [];
var A = [5.65, 3.25, 4.34, 6.78];
var B = ['store.object1', 'store.object2', 'store.object3', 'store.object4'];

for (var i = 0; i < B.length; i++) {
  all.push({
    'A': A[i],
    'B': B[i]
  });
}

all.sort(function(a, b) {
  return a.A - b.A;
});

A = [];
B = [];

for (var i = 0; i < all.length; i++) {
  A.push(all[i].A);
  B.push(all[i].B);
}

console.log(A, B);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Kiran Dash
  • 4,816
  • 12
  • 53
  • 84

4 Answers4

2

You could use a temporary array with the indices and sort it with the values of the first array. Then map the sorted array with the values of array1 and array2.

I use strings for the second array, instead of missing objects.

var array1 = [5.65, 3.25, 4.34, 6.78],
    array2 = ['car.object1', 'car.object2', 'car.object3', 'car.object4'],
    temp = array1.map(function (_, i) { return i; });

temp.sort(function (a, b) { return array1[a] - array1[b]; });

array1 = temp.map(function (a) { return array1[a]; });
array2 = temp.map(function (a) { return array2[a]; });

console.log(temp);
console.log(array1);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Unless you want to implement the sort yourself, one simple way is to combine the entries from the number array with the entries from the object array (at least briefly), sort that, and then (if necessary) extract the result:

// Setup
var car = {
  object1: {name: "object1"},
  object2: {name: "object2"},
  object3: {name: "object3"},
  object4: {name: "object4"}
};
var nums = [5.65, 3.25, 4.34, 6.78];
var objs = [car.object1, car.object2, car.object3, car.object4];

// Combine
var joined = [];
nums.forEach(function(num, index) {
  joined[index] = {num: num, object: objs[index]};
});

// Sort
joined.sort(function(a, b) {
  return a.num - b.num;
});

// Extract
nums = [];
objs = [];
joined.forEach(function(entry, index) {
  nums[index] = entry.num;
  objs[index] = entry.object;
});

console.log(nums);
console.log(objs);
.as-console-wrapper {
  max-height: 100% !important;
}

But rather than combine, sort, and extract, I'd probably just maintain a single array and add each number to its relevant object, so they always travel together.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I just realized this is basically the solution in the question. I'm afraid I took the *"You can just ignore the below answer as I think it is wrong. It does not work."* to heart and skipped right over it. Later I saw the comments between you and ibrahim and looked it it. – T.J. Crowder Mar 18 '17 at 18:02
  • What does it exactly mean? – kind user Mar 18 '17 at 18:06
  • @Kinduser: I don't understand the question. – T.J. Crowder Mar 18 '17 at 18:10
  • Yes. May be the answer is correct. I am still checking with my code here what I did wrong. – Kiran Dash Mar 18 '17 at 18:11
  • Finally I used your snippet. To be honest. I am new to JavaScript and I guess could not debug my code here. So just used your's. Thanks a lot. – Kiran Dash Mar 18 '17 at 18:23
  • 1
    I am now trying to understand how everything works. And also thanks for the idea of having both the data together in one array. I tried that in the beginning. But just because I didn't figure out how to separate them later. I choose to keep them separate. DEADLINE pressure. Anyways thanks. – Kiran Dash Mar 18 '17 at 18:27
1

Here is an ES6 way to do it:

let a = [5.65, 3.25, 4.34, 6.78];
let b = [{ x:1 }, { x:2 }, { x:3 }, { x: 4}];

[a, b] = a.map( (n, i) => [n, b[i]] ) // zip the two arrays together
          .sort( ([n], [m]) => n-m ) // sort the zipped array by number
          .reduce ( ([a,b], [n, o]) => [[...a, n], [...b, o]], [[],[]] ); // unzip 

console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
trincot
  • 317,000
  • 35
  • 244
  • 286
0

I've helped myself with an object containing car.object as the key and it's number as the value. Seems easy&quick solution.

var obj = [{'car.object1': 5.65}, {'car.object2': 3.25}, {'car.object3': 4.34}, {'car.object4': 6.78}],
    objs = obj.sort((a,b) => a[Object.keys(a)] - b[Object.keys(b)]);
    
    console.log(objs.map(v => Object.keys(v)[0]));
    console.log(objs.map(v => v[Object.keys(v)]));
    console.log(objs);
.as-console-wrapper {
  max-height: 100% !important;
}
kind user
  • 40,029
  • 7
  • 67
  • 77
  • Yeah, just DV me without a word – kind user Mar 18 '17 at 18:18
  • Note that your starting point here is not the starting point of the question, which probably explains why the answer was downvoted. If you answer a different question to the one the OP asks, don't be surprised if someone votes it "not useful." (And don't expect downvotes to come with comments. They rarely do. Just take the feedback and look again to see why someone might have considered it not useful. And/or wait for someone to comment, as commenters and downvoters don't necessarily overlap.) – T.J. Crowder Mar 18 '17 at 18:42
  • @T.J.Crowder Actually the starting point is the same in every answer. In one of them the next step is map, or forEach or sort. My next step was to drop these arrays into an object. I don't really see anything wrong in it (: – kind user Mar 18 '17 at 18:51