notes

Beware! Array methods will do shallow copies2020. 11. 19.

const obj1 = { id: 1, name: "obj1" };
const obj2 = { id: 2, name: "obj2" };
const obj3 = { id: 3, name: "obj3" };

const arr = [obj1, obj2, obj3];

const mappedArr = arr.map((obj) => obj);
const filteredArr = arr.filter((obj) => obj.id !== 3);
const reducedArr = arr.reduce((acc, item) => {
  if (item.id === 3) {
    return acc;
  }
  return [...acc, item];
}, []);

const mappedAndSpreadedArr = arr.map((obj) => ({ ...obj }));
const reducedAndSpreadedArr = arr.reduce((acc, item) => {
  if (item.id === 3) {
    return acc;
  }
  return [...acc, { ...item }];
}, []);

console.log(obj1 === mappedArr[0]); // true
console.log(obj1 === mappedAndSpreadedArr[0]); // false

console.log(obj1 === filteredArr[0]); // true

console.log(obj1 === reducedArr[0]); // true
console.log(obj1 === reducedAndSpreadedArr[0]); // false

const findedObj1 = mappedArr.find((obj) => obj.id === 1);
findedObj1.name = "lol";
console.log(obj1.name); // 'lol'

const findedObj2 = mappedAndSpreadedArr.find((obj) => obj.id === 2);
findedObj2.name = "lol";
console.log(obj2.name); // 'obj2'
const obj1 = { id: 1, name: "obj1" };
const obj2 = { id: 2, name: "obj2" };
const obj3 = { id: 3, name: "obj3" };

const arr = [obj1, obj2, obj3];

const mappedArr = arr.map((obj) => obj);
const filteredArr = arr.filter((obj) => obj.id !== 3);
const reducedArr = arr.reduce((acc, item) => {
  if (item.id === 3) {
    return acc;
  }
  return [...acc, item];
}, []);

const mappedAndSpreadedArr = arr.map((obj) => ({ ...obj }));
const reducedAndSpreadedArr = arr.reduce((acc, item) => {
  if (item.id === 3) {
    return acc;
  }
  return [...acc, { ...item }];
}, []);

console.log(obj1 === mappedArr[0]); // true
console.log(obj1 === mappedAndSpreadedArr[0]); // false

console.log(obj1 === filteredArr[0]); // true

console.log(obj1 === reducedArr[0]); // true
console.log(obj1 === reducedAndSpreadedArr[0]); // false

const findedObj1 = mappedArr.find((obj) => obj.id === 1);
findedObj1.name = "lol";
console.log(obj1.name); // 'lol'

const findedObj2 = mappedAndSpreadedArr.find((obj) => obj.id === 2);
findedObj2.name = "lol";
console.log(obj2.name); // 'obj2'

Tags