简体   繁体   English

从数组Javascript / jquery中删除特定元素

[英]Remove specific elements from array Javascript/jquery

Currently I have an array like this: 目前,我有一个像这样的数组:

var list = new Array([
        {id: 0, content: "zero", group: 1},
        {id: 1, content: "one", group: 2},
        {id: 2, content: "two", group: 1},
        {id: 3, content: "three", group: 1},
        {id: 4, content: "four", group: 3},
    ]);

How can I remove the entries where group == 1 using javascript or Jquery? 如何使用JavaScript或Jquery删除group == 1的条目?

Change the array in the following way: 通过以下方式更改数组:

var list = [
  {id: 0, content: "zero", group: 1},
  {id: 1, content: "one", group: 2},
  {id: 2, content: "two", group: 1},
  {id: 3, content: "three", group: 1},
  {id: 4, content: "four", group: 3},
];

otherwise you will end up as an array containing another array. 否则,您将最终成为包含另一个数组的数组。 After that you can filter the array on the following way: 之后,您可以通过以下方式过滤数组:

var filtered = list.filter(function(item) {
  return item.group !== 1
});

console.log(filtered);

You don't need to use new Array - your code creates an array with one element, which is itself an array with five elements. 您不需要使用new Array您的代码将创建一个包含一个元素的数组,该元素本身就是包含五个元素的数组。 You should just use an Array literal: 您应该只使用Array文字:

var list = [
    {id: 0, content: "zero", group: 1},
    {id: 1, content: "one", group: 2},
    {id: 2, content: "two", group: 1},
    {id: 3, content: "three", group: 1},
    {id: 4, content: "four", group: 3},
]

Once you've done that, you can use Array.prototype.filter : 完成此操作后,可以使用Array.prototype.filter

var filtered = list.filter(function(item) {
  return item.group !== 1;
})


If you do mean to build a 2D array you could still use filter: 如果确实要构建2D数组,则仍可以使用滤镜:

var filtered = [list[0].filter(function(item) {
  return item.group !== 1;
})] 

in javascript: 在javascript中:

   list =list.filter(function(item){
     return item.group!=1
   })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM