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}`);