0

How to compare these array object orders are equal.

this.arrayOne = [
{ "data": "India", "seq_id": 1 },
{ "data": "Japan", "seq_id": 2 },
{ "data": "USA", "seq_id": 3 }    
            ]

this.arrayTwo = [
{ "data": "India", "seq_id": 1 },
{ "data": "Japan", "seq_id": 2 },
{ "data": "USA", "seq_id": 3 }    
            ]

Anyone can solve the problem..!?

1

3 Answers 3

2

This code checks if both arrays have the same order. To compare the objects in the arrays it checks if two objects have the same number of properties and all their properties are equal (considering that all properties are of primitive types).

let arrayOne = [
  { "match_value": "India", "seq_id": 1 },
  { "match_value": "Japan", "seq_id": 2 },
  { "match_value": "USA", "seq_id": 3 }    
];

let arrayTwo = [
  { "match_value": "India", "seq_id": 1 },
  { "match_value": "Japan", "seq_id": 2 },
  { "match_value": "USA", "seq_id": 3 }
];

let equal = arrayOne.every((item, i) => {
  let keys = Object.keys(item);
  return keys.length === Object.keys(arrayTwo[i]).length &&
    keys.every(key => arrayTwo[i][key] === item[key]);
});

console.log(equal);

Sign up to request clarification or add additional context in comments.

5 Comments

I got the error on item. "item is not defined" error is displayed.
@A.Sakkeer Well, it's weird because, as you can see, item is defined as an arrow function parameter. And the above script works as expected. Make sure you have no typos in your code. And what version of typescript do you use?
I'm using Angular 5. I don't know how to solve this problem. Can you help me..?.
@A.Sakkeer I don't know what your issue is, but here is the working angular demo
Yes, this is what I expected. But, Still the item is displayed "item is not defined".
1

try something like this :

let a = [
{ "match_value": "India", "seq_id": 1 },
{ "match_value": "Japan", "seq_id": 2 },
{ "match_value": "USA", "seq_id": 3 }    
            ]
let b = [
{ "match_value": "India", "seq_id": 1 },
{ "match_value": "Japan", "seq_id": 2 },
{ "match_value": "USA", "seq_id": 3 }    
            ]

function compare(a, b):boolean{
  let flag = a.length ;
            for (let i = 0, len = a.length; i < len; i++) {
                    if (a[i].match_value === b[i].match_value) {
                        if (a[i].seq_id === b[i].seq_id) {
                          flag --;
                        }
                    }
            }
if(flag)
  return false;
else
  return true;
}

console.log(compare(a,b));

Comments

1

Sometimes i take the easy approach.

function compare(a:any , b:any) {
  return JSON.stringify(a) === JSON.stringify(b);
}

this works for me in Angular 13.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.