0

So I've come across this problem when trying to eliminate the need for duplicated data.

Say I've got a list of objects. I'm separating them based on a specific category. And 2 objects return the same data within the Open 'category'. I don't necessarily want to remove the data, so I think merging/combining is the best way?

If Open category, merge all objects. How can I merge objects? I think .concat() is just for arrays. So is this even possible?

...

Open
------
const dupObjects = this.props.response.flight['open'];
// returns objects that look like this...

Object {delta: Array[1], lambda: Array[0], amount: }
Object {delta: Array[1], lambda: Array[0], amount: 200,000} // duplicate lets combine
Object {delta: Array[1], lambda: Array[0], amount: 200,000} // duplicate lets combine



if (category == 'Open'){
    // merge objects
    const dupObjects = this.props.response.flight['open'];
}

Expected output:

Open:
Delta : Information...    Lambda: Information...   Amount: $0
Delta : Information...    Lambda: Information...   Amount: $200,000
Modelesq
  • 5,192
  • 20
  • 61
  • 88

1 Answers1

1

What you are asking is to remove duplicate objects where you define a duplicate as having the same values using a deep equal. See http://underscorejs.org/#isEqual Below is a sample script that does dedupe of the list. It's not very elegant, but it works:

var objects = [
  {"delta":["St.Louis"],"lambda":[],"amount":200000},
  {"delta":["St.Louis"],"lambda":[],"amount":200000},
  {"delta":["Different"],"lambda":[],"amount":200000}
];

var dedupedList = _.reduce(objects, 
 function(result, item) { 
  var isDupe = _.any(result, function(anyItem) { return _.isEqual(item, anyItem); });
  if (!isDupe) result.push(item);
  return result; 
 }, 
 []);

console.log(dedupedList);
<script src="//jashkenas.github.io/underscore/underscore-min.js"></script>
Daniel Moses
  • 5,872
  • 26
  • 39
  • I really appreciate the answer. Unfortunately I can't use underscore. Since dupObjects's returns each javascript object, I'm just looking to literally combine the 2 or at this point, ignore / remove the duplicate. I'm not sure if it will help me if I post within reactjs channel. – Modelesq May 11 '16 at 17:46
  • I'm not familiar with reactjs. But, conceptually what I have provided should work. You can write your own dedupeCollection function that does a deep equal and removes any that are already there. – Daniel Moses May 11 '16 at 17:58
  • Isn't .push for arrays? – Modelesq May 11 '16 at 18:01