0

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?

3
  • 1
    That is a strange way to create an array, you end up with an array containing the array containing the objects. Commented May 25, 2015 at 9:27
  • It's a very... Java... way to create an array. Commented May 25, 2015 at 9:32
  • You might take a look at splice(). Note: you have to iterate the list using a loop but care for a correct counter when removin elements. Commented May 25, 2015 at 9:33

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

in javascript:

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

Comments

0

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;
})] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.