首页 > 解决方案 > Javascript filter function is returning the removed element and not the new array

问题描述

I am simply trying to remove an element from an array in javascript using the filter function. However, after running this function, newArray is an array with only 1 element - the one I removed.

I wanted an array with the original elements but minus the one I want to remove. How do I get that?

var newArray = comments.filter((comment) => comment.idComment == action.idSectionComments);

Before: enter image description here

After: enter image description here

标签: javascriptarraysarray-filter

解决方案


You are not removing the element, you are picking it. The filter function return all elements in array that satisfy the condition, so you have to reverse the condition to filter all elements that doesn't match the id

var newArray = comments.filter((comment) => comment.idComment !== action.idSectionComments);

推荐阅读