Issue
I have an array with a number of objects like the following:
Each object has the properties
Name, Title, Selected.
I want to make sure that at least one item in each group is selected , if not return an error saying please select an item in the group whatever it is by Entity.
So the list may be like this:
var myarray ==
[0] ->Entity:"Name1", Title:"Mr", Selected:false
[1] ->Entity:"Name1", Title:"Mrs", Selected:false
[2] ->Entity:"Name1", Title:"Ms", Selected:true
[3] ->Entity:"Name1", Title:"Miss", Selected:false
[4] ->Entity:"Name1", Title:"Mr", Selected:false
[5] ->Entity:"Name2", Title:"Mrs", Selected:false
[6] ->Entity:"Name2", Title:"Mr", Selected:false
[7] ->Entity:"Name2", Title:"Mrs", Selected:false
[8] ->Entity:"Name2", Title:"Mrs", Selected:false
[10] ->Entity:"Name2", Title:"Mrs", Selected:false
[11] ->Entity:"Name2", Title:"Miss", Selected:false
[12] ->Entity:"Name3", Title:"Mr", Selected:false
[13] ->Entity:"Name3", Title:"Miss", Selected:false
[14] ->Entity:"Name3", Title:"Miss", Selected:false
[15] ->Entity:"Name3", Title:"Ms", Selected:false
[16] ->Entity:"Name3", Title:"Ms", Selected:false
[17] ->Entity:"Name3", Title:"Mr", Selected:false
[18] ->Entity:"Name4", Title:"Mrs", Selected:false
[19] ->Entity:"Name4", Title:"Mr", Selected:true
[20] ->Entity:"Name4", Title:"Ms", Selected:false
In this scenario there would be a message saying Please select at least one item in Entity , Name2,Name3 as Name1 and Name4 entities have at least one selected value
Solution
You can group the items in Javascript by name as follows:
var map = items.reduce(function(m, current) {
var currentValue = m.get(current.Name);
if (currentValue == undefined) currentValue = false;
m.set(current.Name, currentValue | current.Selected);
return m;
}, new Map());
var withoutSelected = Array.from(map).filter(function(x) {
return !x[1];
}).map(function(x) {
return x[0];
});
Above code uses a map to group by name and to check whether any of the values in the group is selected. Then it converts it to an array that is filtered and mapped to only contain the group names that have no selected items.
See this fiddle.
Answered By - Markus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.