0

Sample JSON:

"employees":[
    {"firstName":"John", "lastName":"Doe", "address ": "India "}, 
    {"firstName":"Anna", "lastName":"Smith", "address ": "Europe "}, 
    {"firstName":"Peter","lastName":"Jones", "address ": " Canada "},
    {"firstName":"hem", "lastName":"fik", "address ": " Europe "}, 
    {"firstName":"kin", "lastName":"ress", "address ": " India "}, 
    {"firstName":"jack","lastName":"pink", "address ": "Canada "}
] 

I want to split above json array into multiple arrays according to address field.I mean one JSON array contains employees having address is "India",another having next and so on.

Smita Ahinave
  • 1,901
  • 7
  • 23
  • 42
  • So, uh, parse the JSON, then loop through the resulting array adding each person to a new object that has keys for the countries (which you add as needed as you loop). Where are you stuck? – nnnnnn Feb 11 '16 at 06:03

1 Answers1

1

Use Array.prototype.filter() function for filtering out the array elements based on condiotions.

var employees = [{
  "firstName": "John",
  "lastName": "Doe",
  "address ": "India "
}, {
  "firstName": "Anna",
  "lastName": "Smith",
  "address ": "Europe "
}, {
  "firstName": "Peter",
  "lastName": "Jones",
  "address ": " Canada "
}, {
  "firstName": "hem",
  "lastName": "fik",
  "address ": " Europe "
}, {
  "firstName": "kin",
  "lastName": "ress",
  "address ": " India "
}, {
  "firstName": "jack",
  "lastName": "pink",
  "address ": "Canada "
}];
var address = employees.map(function(val) {
  return val['address '].trim();
})
var arrays = {};
for (i in address) {
  arrays[address[i]] = employees.filter(function(val) {
    return val['address '].toLowerCase().indexOf(address[i].toLowerCase()) != -1;
  });
}
console.log(arrays);
rrk
  • 15,677
  • 4
  • 29
  • 45