DEV Community

Discussion on: 2 arrays of Same value are not equal in JS.

Collapse
 
smlka profile image
Andrey Smolko

toString() is a not good way (or is good is array's element are primitives). Check that example:

let array1= [1,5,9,14,{a:17}];
let array2= [1,5,9,14,{a:1700}];
console.log(array1.toString() === array2.toString());
// true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Again you showed us another example of why javascript is complicated

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Agree. And we can see the reason why doing

const arr1= [1, 5, 9, 14, {a:17}];
const arr2 = [1, 5, 9, 14, {a:1700}];
arr1.toString()  // '1,5,9,14, [object Object]'
arr2.toString()  // '1,5,9,14, [object Object]'
Enter fullscreen mode Exit fullscreen mode

JSON.stringify on the other hand, works better on this:

const arr1= [1, 5, 9, 14, { a: 17 }];
const arr2 = [ 1, 5, 9, 14, { a: 1700 }];
JSON.stringify(arr1) === JSON.stringify(arr2) // false
Enter fullscreen mode Exit fullscreen mode

because

JSON.stringify(arr1) // '[1,5,9,14,{"a":17}]'
JSON.stringify(arr2) // '[1,5,9,14,{"a":1700}]'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Again complicated but beautiful

Collapse
 
object_required profile image
Nikolai Kim

And with JSON.stringify these two will not be equal:

const arr1 = [ 1, { foo: 2, bar: 3 } ]
const arr2 = [ 1, { bar: 3, foo: 2 } ]
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Actually they are somewhat different (some props are not in the same order).
That's why this question is so tricky 😂

I let you a couple of snippets that can be useful in certain situations:

/**
 * Retrurns the depth of an Object
 * @param {Object} object 
 * @returns {number}
 */
const depthOf = (obj) => {
  let level = 1;
  for (const key in obj) {
    if (!obj.hasOwnProperty(key)) continue;

    if (typeof obj[key] == 'object') {
      let depth = depthOf(obj[key]) + 1;
      level = Math.max(depth, level);
    }
  }
  return level;
};
Enter fullscreen mode Exit fullscreen mode
/**
 * Transforms Object into Array Recursively
 * @param {Object} obj
 * @returns {Array}
 */
const deepObjectToArray = (obj) => {
  let result = obj;
  if (typeof obj === 'object' && !Array.isArray(obj)) {
    result = Object.entries(obj);
    result.forEach((attr) => {
      attr[1] = deepObjectToArray(attr[1]);
    });
  } else if (Array.isArray(obj)) obj.forEach((v, i, a) => (a[i] = deepObjectToArray(v)));

  return result;
};
Enter fullscreen mode Exit fullscreen mode

Discussing them could deal to an entire post probably 😂

Cheers!