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?

asked May 25, 2015 at 9:23
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);
answered May 25, 2015 at 9:31

Comments

0

in javascript:

 list =list.filter(function(item){
 return item.group!=1
 })
answered May 25, 2015 at 9:26

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;
})] 
answered May 25, 2015 at 9:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.