In this list of objects we have value groupID
, Which contains a list.
What I want is to replace the first value in the list with the last value in the previous list.
let testArr = [
{groupID: [1900, 1890, 1880], Letter: "A"},
{groupID:[1888, 1898, 1908, 1918, 1928, 1938], Letter: "B"},
{groupID: [1927, 1917, 1907], Letter: "A"},
{groupID: [1912, 1922, 1932, 1942, 2012, 2022, 2032, 2042], Letter: "B"},
{groupID: [2039, 2029, 2019, 2009], Letter: "A"},
{groupID: [2013, 2023, 2033], Letter: "B"},
]
The result is:
let testArr = [
{groupID: [1900, 1890, 1880], Letter: "A"},
{groupID:[1880, 1898, 1908, 1918, 1928, 1938], Letter: "B"},
{groupID: [1938, 1917, 1907], Letter: "A"},
{groupID: [1907, 1922, 1932, 1942, 2012, 2022, 2032, 2042], Letter: "B"},
{groupID: [2042, 2029, 2019, 2009], Letter: "A"},
{groupID: [2009, 2023, 2033], Letter: "B"},
]
I have this code, but it’s silly and doesn’t work with async and await
:
let add = []
for (let i = 0; i < testArr.length; i++){
if (testArr[i].groupID.length != 0){
add.push(testArr[i].groupID[testArr[i].groupID.length-1])
}
}
for (let i = 1; i < testArr.length; i++){
testArr[i].groupID.splice(0,1, add[i-1])
}
and Thanks in advance.
3
Answers
I don’t understand why your code needs to work with
async
/await
but a possible solution to your problem could look as follows:I am not sure if you’re trying to replace the elements in the same array of objects or need to return a new array. However, here is a solution to replace the elements in the same array.
Update: Based on your comment, it seems you need this transformation to happen from the end to the beginning of the list. I have commented my previous code and kept it for reference, though.
Please note that there could be multiple solutions to this depending upon what exactly you need to achieve. Also, you need to explain what do you mean by running this code with
async
andawait
?The OP’s specification can be implemented almost literally …