get the objects that are repeated in an array of JSON objects with javascript (JQuery)

2

I give as an example the following array of objects in JSON:

[{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}]. 

I would like to obtain an array with the repeated objects (note that in the example the object is repeated with id: aaa), something like this:

[{"id":"bbb","uns":"023"},REPETIDOS[{"id":"aaa","uns":"123"}],{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}]

How could I get the elements repeated with javascript / Jq? with a simple array I get it, but with an array of objects it resists me.

    
asked by miss Robot 06.06.2017 в 10:46
source

1 answer

4

The only difference with the code you use to get the duplicates of numerical values is that you will need:

  • To order the array a comparison function that decides if one object is less than another
  • To obtain duplicates a comparison function that decides if two objects are equal

var data = [{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}];

var isEqualFunction = function(a, b){
  return a.id === b.id && a.uns === b.uns;
}

var compareFunction = function(a, b){
  return a.id === b.id
    ? (a.uns === b.uns ? 0 : (a.uns < b.uns ? -1 : 1))
    : (a.id < b.id ? -1 : 1);
}

var arrayOrdenado = data.sort(compareFunction);
var repetidos = []; 
for (var i = 0; i < arrayOrdenado.length - 1; i++) { 
  if (isEqualFunction(arrayOrdenado[i + 1], arrayOrdenado[i])) 
  {
    repetidos.push(arrayOrdenado[i]); 
  } 
} 
console.log(repetidos);

You could also use the same function:

var data = [{"id":"aaa","uns":"123"},{"id":"bbb","uns":"023"},{"id":"aaa","uns":"123"},{"id":"ccc","uns":"765"},{"id":"ddd","uns":"256"}];

var compareFunction = function(a, b){
  return a.id === b.id
    ? (a.uns === b.uns ? 0 : (a.uns < b.uns ? -1 : 1))
    : (a.id < b.id ? -1 : 1);
}

var arrayOrdenado = data.sort(compareFunction);
var repetidos = []; 
for (var i = 0; i < arrayOrdenado.length - 1; i++) { 
  if (compareFunction(arrayOrdenado[i + 1], arrayOrdenado[i]) === 0) 
  {
    repetidos.push(arrayOrdenado[i]); 
  } 
} 
console.log(repetidos);
    
answered by 06.06.2017 / 11:18
source