I have a set of objects retrieved from an API.
let objectList = [
{title: 'Big Bang Theory'},
{title: 'Breaking Bad'},
{title: 'Stranger Things'},
{title: 'Game of Thrones'},
{title: 'Money Heist'}
];
In my data, I want Game of Thrones
to always appear before Stranger Things
, while keeping the other elements in their original order. Sometimes the API will provide them correctly arranged, but sometimes they will be reversed like in the example above.
Does anyone have suggestions on the most efficient approach for achieving this?
I am aware of using a loop and conditional statements, but I believe there might be a more optimal solution available.
for(let i = 0; i < objectList.length; i++){
if(objectList[i].title === 'Game of Thrones' && objectList[i - 1].name === 'Stranger Things'){
let tempObject = objectList[i];
objectList[i] = objectList[i - 1];
objectList[i - 1] = tempObject;
}
}
Alternatively, should I consider creating a new array rather than modifying the existing one?