Merge Objects that have some similarity

Asked

Viewed 60 times

2

Is there any way to join objects that have some similarity ? For example:

var exemplo = [
  {'Title': 'exemple1', 'id': 15},
  {'Title': 'exemple1', 'id': 15},
  {'Title': 'exemple2', 'id': 20}
]

And stay that way:

var exemplo = [
  {'Title': 'exemple1', 'id': 15},
  {'Title': 'exemple2', 'id': 20},
]

Or catch with a loop only one of the objects that are similar?

1 answer

4


You can use the function reduce of array to scroll through each item and check if it is already in another array results (which will be populated within the reduce).

const exemplo = [
  {'Title': 'exemple1', 'id': 15},
  {'Title': 'exemple1', 'id': 15},
  {'Title': 'exemple2', 'id': 20},
];

const resultado = exemplo.reduce((acumulador, item) => {
  const filtrados = acumulador.filter((a) => a.Title == item.Title && a.id == item.id).length;
  filtrados > 0 || acumulador.push(item);
  return acumulador;
}, []);

console.log(resultado);

reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15


filter

The method filter() creates a new array with all the elements that passed the test implemented by the function provided.

function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered é [12, 130, 44]
console.log(filtered);

  • there is some way to get the latest(the lowest) using the same script ? for example instead of getting the example[0] catch the example[1' ?

  • @Joãovictor what is the difference if they are equal??

  • with the script you made it picks the first of which are similar, I wanted to somehow catch the last similar

  • @Joãovictor I understood, I just didn’t understand the purpose

  • It’s kind of hard to explain more is this. I created a history script that when doing some actions on my site it arrow an object in an array, to record the action, and on another page I take these objects and place them in a list. At the time of putting in the list I wanted only the latest similar objects added in the array, not to get a huge list

  • @Joãovictor seems to me that what you really want to do is not what you asked. You can create another question with a more complete and closer example than you want, because to make this change the answer would be completely different and would not make sense with this question

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.