简体   繁体   中英

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?

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. You should just use an Array literal:

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 :

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


If you do mean to build a 2D array you could still use filter:

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

in javascript:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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