1

I've got model like this:

class Model {
  from: number;
  values: { [id: string]: number };
  originalValues: { [id: string]: number };
}

Then I create arr = Model[] = [];

I need to check whether values match originalValues and that's how I do it:

 for (let edited of this.arr) {
  edited.model.forEach(m => {
    if (Object.values(m.originalValues) == Object.values(m.values)) {
    // console.log(equal);
    } else {
      // not equal
    }
  });

But even though they are equal, I always get not equal. Example of how values and original values look like: originalValues: {11c33aaaaaaaaasafsdf33: 23.5} What I'm doing wrong here?

mudin
  • 2,672
  • 2
  • 17
  • 45
user122222
  • 2,179
  • 4
  • 35
  • 78
  • 1
    You're comparing the array references, not the array contents. – Robby Cornelissen Dec 20 '18 at 09:01
  • 1
    `Object.values` will get the values only, not the keys, hence if a key is missing the control will be lost. Besides, since it looks like you are working with `primitives`, you may find faster approaches. The big problem, right now, is that you are comparing **array references** instead of **values**, hence the reference is never the same, in that case specifically. Take a look at this: https://stackoverflow.com/questions/1068834/object-comparison-in-javascript . Also, are the keys and values **always in the same order**? – briosheje Dec 20 '18 at 09:02
  • 1
    Maybe try converting the values to string using ```JSON.stringify``` and then compare the strings? – JO3-W3B-D3V Dec 20 '18 at 09:04

2 Answers2

2

const log = args => console.log(args);


const array = [{
  values: [1, 2, 3],
  otherValues: [1, 2, 3]
}, {
  values: [1, 2, 3],
  otherValues: [1, 2, 3, 'a', 'b', 'c']
}, {
  values: [1, 2, 3],
  otherValues: [3, 2, 1]
},{
  values: [{ name: 'Jack' }, 'a', 'b', 'c', 1, 2, 3],
  otherValues: [1, 2, 3, 'a', 'b', 'c', { name: 'Jack' }]
}];


log('\nOriginal');
array.forEach(o => {
  const bool = JSON.stringify(o.values) === JSON.stringify(o.otherValues);
  log(bool);
});


log('\nEdit');
array.forEach(o => {
  const v1 = Object.values(o.values).sort(), v2 = Object.values(o.otherValues).sort();
  const bool = JSON.stringify(v1) === JSON.stringify(v2);
  log(bool);
});
JO3-W3B-D3V
  • 2,124
  • 11
  • 30
  • 1
    Just a side note: this will only work if **keys holds the same order in both objects**. You may think about providing a solution where that condition is not met. – briosheje Dec 20 '18 at 09:14
  • @briosheje That's a good point, I've just made an edit to cater for that to a certain extent. – JO3-W3B-D3V Dec 20 '18 at 09:21
1

If you have only number,strings, object and array then you can simply

JSON.stringify(originalValues)==JSON.stringify(values);
Aman Jain
  • 384
  • 1
  • 3
  • 15