unknown123
unknown123

Reputation: 309

Why the output of .splice is a single object?

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

Answers (4)

maksymhlushek
maksymhlushek

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

Mohammed Nidhal
Mohammed Nidhal

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

Moufeed Juboqji
Moufeed Juboqji

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

slebetman
slebetman

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

Related Questions