javascript - 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);
解决方案
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);
推荐阅读
- c# - 如何使用 linq 将多个模型组合成一个模型
- c - 在 C 中创建一个字符串数组
- r - R中没有循环的假阳性和假阴性
- javascript - 全局变量未在函数内部更新
- jquery - ReactJS react-bootstrap From.Control 日期选择器格式
- apache-spark - 启用动态分区覆盖时,S3 优化写入器无法正常工作
- toggle - SwiftUI - 使用切换 - 控制台日志:“无效模式 'kCFRunLoopCommonModes'” - didSet 不起作用
- android - DEPLHI - 试图在 Android 中获取库图像的 EXIF 数据
- java - 即使孩子不在也能获取父母
- azure-devops - 如何正确替换/删除 azure 私人代理