Arpan Banerjee
Arpan Banerjee

Reputation: 1016

Why map() operation on a javascript array to copy it to another array after changing an element returning undefined?

let array = [
  { id: 1, name: "One" },
  { id: 2, name: "Two" },
  { id: 3, name: "Three" },
];

I have this array, I want to copy it to another array after changing one element, but my code does not work out.

array_copy = array.map((element) => {
  if (element.id === 2) {
    element.name = "name changed";
  } 
});

console.log(array_copy);

I am getting this output--

(3) [undefined, undefined, undefined]

I am new to js and self learning it, can u pls help me understand this?

Here is the link of the question Copy javaScript array by changing one element

--I tried to answer . What is wrong with my logic/approach?

Upvotes: 1

Views: 428

Answers (4)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You need to add the return statement otherwise it will be undefined as expected but Array map changes the main array elements so log the main array and see you'll get modified it also.

let array = [
  { id: 1, name: "One" },
  { id: 2, name: "Two" },
  { id: 3, name: "Three" },
];

array_copy = array.map((element) => {
  if (element.id === 2) {
    element.name = "name changed";
  } 
  return element;
});

console.log(array,array_copy);

Upvotes: 1

Mikhail Aksenov
Mikhail Aksenov

Reputation: 934

If you don't want to change your source array you have to copy element from the source array and return the copied and modified elements instead.

let array = [
  { id: 1, name: "One" },
  { id: 2, name: "Two" },
  { id: 3, name: "Three" },
];

let array_copy = array.map((element) => {
  let copy_element = Object.assign({}, element)
  if (copy_element.id === 2) {
       copy_element.name = "name changed";
  } 
  return copy_element ;

});

console.log('array_copy', array_copy);

console.log('array',array);

Upvotes: 2

Mohammad Manzoor Alam
Mohammad Manzoor Alam

Reputation: 101

You are missing the return statement, thats why you getting undefined.

this is the correct code

array_copy = array.map((element) => {
  console.log(element.id);
  if (element.id === 2) {
    element.name = "name changed";
  } 
return element;
});

console.log(array_copy);

Upvotes: 1

You need to return something from the function you are using for the map-callback

Do this instead:

array_copy = array.map((element) => {
  console.log(element.id);
  if (element.id === 2) {
    element.name = "name changed";
  } 
return element
});

As you are not returning anything from the function, you are getting undefined for each iteration

Upvotes: 3

Related Questions