다음과 같은 일부 영화에 대한 데이터를 포함하는 객체 배열이 있다고 가정합니다.
const arr = [
{id: "1", name: "Snatch", type: "crime"},
{id: "2", name: "Witches of Eastwick", type: "comedy"},
{id: "3", name: "X-Men", type: "action"},
{id: "4", name: "Ordinary People", type: "drama"},
{id: "5", name: "Billy Elliot", type: "drama"},
{id: "6", name: "Toy Story", type: "children"}
]; 첫 번째 인수로 하나의 배열을, 두 번째 인수로 id 문자열을 취하는 JavaScript 함수를 작성해야 합니다. 그런 다음 함수는 해당 ID로 개체를 검색해야 하며 배열에 해당 개체가 포함되어 있으면 배열에서 제거해야 합니다.
예시
이에 대한 코드는 -
const arr = [
{id: "1", name: "Snatch", type: "crime"},
{id: "2", name: "Witches of Eastwick", type: "comedy"},
{id: "3", name: "X-Men", type: "action"},
{id: "4", name: "Ordinary People", type: "drama"},
{id: "5", name: "Billy Elliot", type: "drama"},
{id: "6", name: "Toy Story", type: "children"}
];
const removeById = (arr, id) => {
const requiredIndex = arr.findIndex(el => {
return el.id === String(id);
});
if(requiredIndex === -1){
return false;
};
return !!arr.splice(requiredIndex, 1);
};
removeById(arr, 5);
console.log(arr); 출력
콘솔의 출력은 -
[
{ id: '1', name: 'Snatch', type: 'crime' },
{ id: '2', name: 'Witches of Eastwick', type: 'comedy' },
{ id: '3', name: 'X-Men', type: 'action' },
{ id: '4', name: 'Ordinary People', type: 'drama' },
{ id: '6', name: 'Toy Story', type: 'children' }
]