0

Context: A program I'm writing generates an array that contains arrays. I would like to sort the array according to the value of arrayElement[0] (i.e. the first value within each sub-array).

In the example below, I take the arrayElement[0] values, put them into a separate array (tempSortArray) and sort them. Then I run a nested loop to take items from the original foo array and put them, in order, into the finalFooArray.

Actual problem: In case there are several array items with the same arrayElement[0] value, I have added y[0] = false after adding y to the finalFooArray. This ought to prevent the code from constantly adding the same elements over and over.

However, the resultant array is this: false,[object Object],[object Object],false,[object Object],[object Object],false,[object Object],[object Object], i.e. the y[0] = false somehow makes its way into the array, even though I changed the value after putting the value into the array.

Can anyone explain why this is happening and how I can prevent it?

var foo = [
    [28888888, {x: 12,y: 3},{x: 1,y: 45678}],
    [78, {x: 54,y: 3}, {x: 3,y: 3}],
    [456, {x: 1,y: 76543}, {x: 765432,y: 7}]
];
let tempSortArray = [];
let finalFooArray = [];
foo.forEach((item) => {
    tempSortArray.push(item[0]);
});
tempSortArray.sort(function(a, b) {
    return a - b
});
   
for (let x of tempSortArray) {
    for (let y of foo) {
        if (x == y[0]) {
            finalFooArray.push(y);
            y[0] = false; // Change the value of y[0] just in case there are several items with the same y[0] value
        }
    }
}
console.log(`The sorted array goes like this: ${finalFooArray}`);
hal9000
  • 3
  • 2
  • also [How to sort 2 dimensional array by column value?](https://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value) and [Sort 2d array by first element in JavaScript](https://stackoverflow.com/questions/62619436/sort-2d-array-by-first-element-in-javascript) – pilchard Jul 25 '22 at 23:02

2 Answers2

0

Why not just sort by the first item of each array?

var foo = [
    [28888888, {x: 12,y: 3},{x: 1,y: 45678}],
    [78, {x: 54,y: 3}, {x: 3,y: 3}],
    [456, {x: 1,y: 76543}, {x: 765432,y: 7}]
];


console.log(foo.sort(function(a, b) {
  if (a[0] > b[0]) return 1;
  if (a[0] < b[0]) return -1;
  return 0
}))
IT goldman
  • 14,885
  • 2
  • 14
  • 28
0

You don't need a temporary array; just directly sort the array, returning the difference between the first elements in the callback.

var foo = [
    [28888888, {x: 12,y: 3},{x: 1,y: 45678}],
    [78, {x: 54,y: 3}, {x: 3,y: 3}],
    [456, {x: 1,y: 76543}, {x: 765432,y: 7}]
];
foo.sort((a, b)=>a[0] - b[0]);
console.log(JSON.stringify(foo));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80