2

I map array of objects and try to add property and return new array and log it. But turned out it changes the original array too... Why does this happen? I believe it is some sort of object trick.

var students = [
    { name: 'nika', age: 25 },
    { name: 'goga', age: 11 },
    { name: 'saba', age: 20 },
    { name: 'tedo', age: 35 },
    { name: 'gio', age: 15 },
    { name: 'lasha', age: 5 },
    { name: 'sandro', age: 8 },
];

function solution(arr) {
    let newArr = arr.map(function (item) {
        if (item.age < 18) {
            item.forbidden = true;
        }
        return item;
    });

    console.log(newArr);
    console.log(students);

}

solution(students);

I want solution in ES5

KoboldMines
  • 428
  • 2
  • 6
  • 21

2 Answers2

1

You could create a copy from the object which does not share the same object reference.

function solution(arr) {
    return arr.map(function (item) {
        item = JSON.parse(JSON.stringify(item));

        if (item.age < 18) {
            item.forbidden = true;
        }
        return item;
    });
}


var students = [
    { name: 'nika', age: 25 },
    { name: 'goga', age: 11 },
    { name: 'saba', age: 20 },
    { name: 'tedo', age: 35 },
    { name: 'gio', age: 15 },
    { name: 'lasha', age: 5 },
    { name: 'sandro', age: 8 },
];

console.log(solution(students));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Nina Scholz correctly points out that a solution is to create a copy of each object within the function in the map method and alludes to why this is necessary: The map method is creating a new array of objects, but those objects share the same references as the objects in the original array. Thus, any changes made to the objects reflects in both arrays.

Anon
  • 9
  • 4