3

How do I update first item of time using map?

const myArr = [{
  day: 1,
  time: [1200, 1400]
}]

newTime = 1300;
myNewArr = myArr.map(d => {
  return {
    day: d.day,
    time: [newTime] // but this don't care about order
  }
})
console.log(myNewArr)

which is 1200, replace it with says 1300, but keep 1400 as the second item? or vice versa replace 1400 with another number.

2
  • 1
    Why don't you do it directly with myArr[0].time[0] = 1300? Commented Apr 5, 2018 at 7:17
  • Use spread operator instead Commented Apr 5, 2018 at 7:19

2 Answers 2

4

You could use Object.assign and take an object with the wanted index for replacement.

var myArr = [{ day: 1, time: [1200, 1400] }],
    newTime = 1300,
    myNewArr = myArr.map(
        ({ day, time }) => ({ day, time: Object.assign([], time, { 0: newTime }) })
    );

console.log(myNewArr);

Sign up to request clarification or add additional context in comments.

1 Comment

wow didn't know it can take index like that, I can't do this with spread operator right?
3

Considering that you don't want to update the original array, you could use slice with spread syntax to update the data like

const myArr = [{
  day: 1,
  time: [1200, 1400]
}]

newTime = 1300;
myNewArr = myArr.map(d => {
  return {
    day: d.day,
    time: [newTime, ...d.time.slice(1)]
  }
})
console.log(myNewArr)

Please note that mapping over your data and updating like above will update the entire list of objects.

You could use Object.assign instead of spread syntax as @NinaScholz also suggested, That way you can update any particular index. It comes from the fact that array accepts integer indices

const myArr = [{
  day: 1,
  time: [1200, 1400]
}]

newTime = 1300;
myNewArr = myArr.map(d => {
  return {
    day: d.day,
    time: Object.assign([], time, {1: newTime})
  }
})
console.log(myNewArr)

9 Comments

@T.J.Crowder, sorry wrong choice of words from my part
do I have to change anything in this line time: [newTime, ...d.time.slice(1)] if I want to update the second array instead of the first one?
yes , time: [...d.time.slice(0, index), newTime, ...d.time.slice(index + 1)] where index is the index that you want to update, this syntax will work with index 0 as well
@SharonChai: Not as readable, and less efficient. But for the index-0 case in your question, spread would be nice and readable (but still less efficient than Nina's assign because of the temporary array).
Well, efficiency is rarely all that important. You have to be dealing with a massive array, or doing the operation a lot. :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.