MrBuggy MrBuggy - 5 months ago 14
Javascript Question

Exchange items in array without temp vars

Hi I've got follow object:

myList = {
Items: [
{
ID: 1,
Name: "last"
},
{
ID: 2,
Name: "before last"
},
{
ID: 3,
Name: "second"
},
{
ID: 4,
Name: "first"
}
]
};


The order in my array is now: 1, 2, 3 and 4.

Now I'd like to exchange the item with ID == 4 with the first one (ID == 1) and the item with the ID == 3 with the second one (ID == 2). Is there a way to do this without some temp vars? So that I probably can say, put the item with ID == 4 on the first index and the other would automaticly move down and don't be overwritten? And if there isn't any way without temp vars, how should I do this best with such temp vars?

Thanks and cheers

Answer

myList = {
            Items: [
                {
                    ID: 1,
                    Name: "last"
                },
                {
                    ID: 2,
                    Name: "before last"
                },
                {
                    ID: 3,
                    Name: "second"
                }, 
                {
                    ID: 4,
                    Name: "first"
                }
            ]
        };
console.log(myList.Items);

myList.Items = {myList: myList.Items.reverse()};

console.log(myList.Items);

Comments