3

I'm having an array of objects These objects are coming from two different input fields on my form. They are identified by ids.

Field one is id:1 and field two is id:2. How can I split them into two arrays based on their ids. For example id:1 objects to be stored in array1 and id:2 in array2. I don't want to hardcode as if more input fields were created this would make some mess.

"values":[{"id":"1","description":"123"},
          {"id":"1","description":"456"},
          {"id":"2","description":"456"}]

2 Answers 2

4

In this case you need to use groupBy as filter, if you interesting to figure out how it works read it

angular-filter#groupby

Remember you don't need to make a new filter or other models to handle it just use it! save your time

but solution is so easy:

var result = $filter("groupBy")(values, 'id');
//this result will return 1: [{"id":"1","description":"123"},{"id":"1","description":"456"}] & 2: [{"id":"2","description":"456"}]
for(var item in result){
   //item return all keys (ids) => 1, 2
   //result[item] return all objects related to a key OR id
   //so you can do anything here
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to make 'result' be an array instead of an object? I know you can wrap [ ] around values, however this makes it an array of an object of...
If you think about groupBy you figure out the result must be object, but for your answers YES we can convert it... see the update
3

You can generate a list of uniques id by using Set . Then, with array.prototype.reduce along with array.prototype.filter, you can dynamically build an object that wraps all the generated arrays for each id:

var values = [
	{"id":"1","description":"123"},
	{"id":"1","description":"456"},
	{"id":"2","description":"456"}
];

var ids = [...new Set(values.map(v => v.id))];
var res = ids.reduce((m, o) => (m[`array${o}`] = values.filter(v => v.id === o), m), {});

console.log(res);

Comments

Your Answer

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.