0

Okay, I think my problem is a common Javascript thing.
A have a simple ajax call with a success callback.
The ajax call returns a list of products. Now I need a list of these products sorted by Id and sorted by Date.

The list of products contains objects like this one:

{
    Id: 12345,
    LastModified: "2015-01-05T14:53:18.493Z",
    Name: "Beer"
}

Here is my sample code:

var prodsAll; 
var prodsNew;

$.ajax({
    url:"getProds.php",  
    success:function(res) {

        prodsAll= res;
        prodsNew = res;

        prodAll.sort(function (a, b) {
            return a.Id > b.Id ? 1 : -1;
        });

        prodNew.sort(function (a, b) {
            return new Date(b.LastModified).getTime() - new Date(a.LastModified).getTime();
        });


    }
});

Whatever I do, it looks that all of my lists are changed!?
When I do:

console.log(res);
console.log(prodsAll);
console.log(prodsNew);

I always get the same result :-/
How is it possible to change the lists independent!?

chris
  • 4,827
  • 6
  • 35
  • 53
  • 1
    `prodsAll` and `prodsNew` are referencing the same original array. When you sort `prodsAll` and `prodsNew` you're still sorting `res`. You'll need to [clone the list](http://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop) first. – James Thorpe Jan 05 '15 at 14:44
  • 1
    Just a side note, and it probably shouldn't matter here, but the function you are passing to `prodAll.sort()` is incorrect. It should return `0` if `a.Id` and `b.Id` are equal. You can do this by changing it to use `return a.Id - b.Id;`. – JLRishe Jan 05 '15 at 14:49

1 Answers1

2

This is the problem

prodsAll= res;
prodsNew = res;

These have the same reference to a single array, you make a fresh copy of it like this

prodsAll = res;
prodsNew = res.slice();
axelduch
  • 10,769
  • 2
  • 31
  • 50