-1

I'm trying several methods to grouping an array of abjects json but I can not do it, this is the initial array:

{_id: "455", name: "ALBACETE"}
{_id: "455", name: "ALLICANTE"}
{zone: {_id: "zone1", name: "zone1"}, _id: "143", name: "ALCALA"}
{zone: {_id: "zone1", name: "zone1"}, _id: "144", name: "OTRO"}
{zone: {_id: "zone2", name: "zone2"}, _id: "144", name: "OTRO MAS"}

That is, there are elements of the array that have no zone and others if.

I would expect a result like this:

{_id: "455", name: "ALBACETE"}
{_id: "455", name: "ALLICANTE"}
{zone: {_id: "zone1", name: "zone1"}, _id: "144", name: "OTRO"}
{zone: {_id: "zone2", name: "zone2"}, _id: "144", name: "OTRO MAS"}

That is, it is grouped by zone (zone1 is not repeated).

I try this:

const q = [
     { zone: { _id: "zone1", name: "zone1" }, _id: "143", name: "ALCALA" },
     { zone: { _id: "zone1", name: "zone1" }, _id: "144", name: "OTRO" },
     { zone: { _id: "zone2", name: "zone2" }, _id: "144", name: "OTRO MAS" },
     { _id: "455", name: "ALBACETE" }
     {_id: "455", name: "ALLICANTE"}
 ];``


let ret = [];

let result = q.filter( x => {
  if(!ret.includes(x._id)) {
    ret.push(x._id);
    return true;
  }
  return false;
});

But the output does not filter by the object "zone":

[ 
   { zone: { _id: 'zone1', name: 'zone1' }, _id: '143', name: 'ALCALA' },
   { zone: { _id: 'zone1', name: 'zone1' }, _id: '144', name: 'OTRO' },
   { _id: '455', name: 'ALBACETE' } 
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Avellino
  • 61
  • 7
  • 1
    That's not grouping, but rather removing "duplicates". Why is the element with the name "OTRO" kept, and not "ALCALA", since that's the first element in that array with zone id 1 – Luca Kiebel Aug 11 '18 at 15:11
  • Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Aug 11 '18 at 15:12
  • Is that the zone should not be repeated: zone: "zone1". Can you help me? I would appreciate. – Avellino Aug 11 '18 at 15:20
  • Filtering criteria given is far too vague and that isn't even an array that we can work with without doing our own restructuring. Always provide a [mcve]. Take a few minutes to read through [ask] then edit the question to explain the filtering in more detail – charlietfl Aug 11 '18 at 15:31
  • The problem is that I can not access the zone object – Avellino Aug 11 '18 at 15:51

1 Answers1

0

Ok, I already managed to solve the problem in this way: A forEach to go through the array and JSON.stringify() to compare the values.

Avellino
  • 61
  • 7