Reputation: 309
I am working on my API. At this point, I want to replace the first object of an array such as:
If given data is:
const data = ["1", 2, 3, 4, 5, 6]
then I want: OUTPUT AS:
["New_text", 2, 3, 4, 5]
For this, I tried .splice function:
const new_data = data.splice(0, 1, "New_text")
But I am getting ["1"] as output. How can I do this?
Upvotes: 2
Views: 432
Reputation: 106
the splice method works fine for you. but if the task is only to change first element in array you actually instead of splice can use this
const data = ["1", 2, 3, 4, 5, 6]
data.shift()
data.unshift("New_text")
// or just
data[0] = "New_text"
Upvotes: 1
Reputation: 62
splice make a new array made with the items you deleted ONLY.
you need to put the new 'New_text' in the original array After using splice,
try unshift method to put 'New_text' as the first element.
Upvotes: 0
Reputation: 700
splice
method return a new array of deleted items. It also mutates the original array
Try
const data = ['1', 2, 3, 4, 5, 6];
data.splice(0, 1);
data.unshift('New_text');
console.log(data);
Upvotes: 2
Reputation: 113974
It is working correctly but you are misunderstanding how it works:
const deleted_data = data.splice(0, 1, "New_text");
console.log(deleted_data); // [1]
console.log(data); // ["New_text", 2, 3, 4, 5, 6]
// ^
// |
// NOTE: "data" itself is modified by splice
If you really want to insist that the added data be part of a new array you need to manually copy the old array to a new array:
const new_data = data.slice(); // copy old array
new_data.splice(0, 1, "New_text");
// ^
// |
// NOTE: new_data, not data !
Upvotes: 1