0

Replace an employee aged > 50 with a younger employee.

I am trying to update an item inside an array I am forEach()ing on. Assigning the current fails while noting the index and replacing the item after forEach() block works. Kindly explain this behaviour?

var youngerEmployee = {
  name: {
    first: 'B',
    last: 'C'
  },
  age: 25
}

var employees = [
  {
    name: {
      first: 'X',
      last: 'Y'
    },
    age: 45
  },
  {
    name: {
      first: 'A',
      last: 'B'
    },
    age: 54
  }
];

/* --- Failed approach --- */

employees.forEach(

  (employee) => {

    if(employee.age > 50) {

      employee = youngerEmployee;

    }

  }

);

console.log(employees);

/* --- Successful approach --- */

var i = -1;

employees.forEach(

  (employee, index) => {

    if(employee.age > 50) {

      i = index;

    }

  }

);

employees[i] = youngerEmployee;

console.log(employees);

JSBin

Karma
  • 2,196
  • 1
  • 22
  • 30
  • `employee` does not point to an array element, it just references it. Therefore changing `employee` does not change the array. Please read the duplicate for further explanation, if you got further questions feel free to ask :) – Jonas Wilms May 01 '18 at 11:42
  • @JonasW.Your explanation isn't clear. Agreed that `employee` is a reference and not the actual element. Why is assigning it to another object not updating its reference? Also, I don' think this is a duplicate. The questions might cover the same principle. – Karma May 01 '18 at 11:45

2 Answers2

1

In your "failed approach", the employees array is unchanged because employee references the current employee in the array. By assigning employee = youngerEmployee you change the reference which otherwise leaves the employees array untouched.

phuzi
  • 12,078
  • 3
  • 26
  • 50
0

Use map instead of forEach it will not manipulate the original array

var youngerEmployee = {
  name: {
    first: 'B',
    last: 'C'
  },
  age: 25
}

var employees = [{
    name: {
      first: 'X',
      last: 'Y'
    },
    age: 45
  },
  {
    name: {
      first: 'A',
      last: 'B'
    },
    age: 54
  }
];
var x = employees.map(function(item) {
  if (item.age > 50) {
    item = youngerEmployee
  }
  return item

});
console.log(x)
brk
  • 48,835
  • 10
  • 56
  • 78