How to compare two array of objects?

javascript compare two arrays of objects
javascript compare two arrays of objects for matches
javascript compare two arrays for matches
comparing two arrays in javascript returning differences
javascript difference between two arrays of objects
compare two arrays javascript
es6 compare arrays
javascript check if two arrays have same elements

I have a class A:

class A {
   var identifier: String?
   var quantity: Int = 0
}

Two arrays of A instances:

var array1: [A] = [a1, a2, a3, a4]
var array2: [A] = [a5, a6, a7, a8]

I don't know which is the best way to check: array1==array2 if a1.identifier == a5.identifier, a2.identifier == a6.identifier, a3.identifier==a7.identifier, a4.identifier==a8.identifier in Swift.

Please help me...

You can try like this:

let result = zip(array1, array2).enumerated().filter() {
    $1.0 == $1.1
}.map{$0.0}

How to get the difference between two arrays of objects in JavaScript, This will return the difference between two arrays of objects, using the key value to compare them. Note two things with the same value will not be returned,  Sorting takes O (n*logn) time if the array contains n elements and finally, our comparing function's loop takes O (n) time. Effectively, our code now runs in O (nlogn) time which is a good upgrade from the previous code that took O (n^2) time!

Assume your data like that:

struct Person
    {
        let name: String
        let id:  Int
    }

    var people1 = [
        Person(name: "Quang Hà", id: 42),
        Person(name: "Lý Hải", id: 23),
        Person(name: "Maria", id: 99)
    ]

    var people2 = [
        Person(name: "Maria yyy", id: 99),
        Person(name: "Billy", id: 42),
        Person(name: "David", id: 23)
    ]

This is the method to compare two arrays of people with id:

func areArrayPeopleEqual(people1:[Person], people2: [Person]) -> Bool {
    var array1 = people1
    var array2 = people2

    // Don't equal size => false
    if array1.count != array2.count {
        return false
    }

    // sort two arrays
    array1.sortInPlace() { $0.id > $1.id }
    array2.sortInPlace() {$0.id > $1.id }

    // get count of the matched items
    let result = zip(array1, array2).enumerate().filter() {
        $1.0.id == $1.1.id
        }.count

    if result == array1.count {
        return true
    }

    return false
}

Check if two arrays or objects are equal with JavaScript, To properly compare two arrays or objects, we need to check: That they're the same object type (array vs. object). That they have the same  To properly compare two arrays or objects, we need to check: That they’re the same object type (array vs. object). That they have the same number of items. That each item is equal to its counterpart in the other array or object. That they’re the same object type (array vs. object vs. string vs. number vs. function). That they have the same value.

Swift 4

The following method makes it much more easy.

Method 1 - Using Equatable Protocol

Step1 - Make your class 'A' equatable as follows

extension A: Equatable {
    static func ==(lhs: A, rhs: A) -> Bool {
        // Using "identifier" property for comparison
        return lhs.identifier == rhs.identifier
    }
}

Step2 - Sort your arrays in ascending or descending order

let lhsArray = array1.sorted(by: { $0.identifier < $1.identifier })
let rhsArray = array2.sorted(by: { $0.identifier < $1.identifier })

Step3 - Use == or elementsEqual comparison

let isEqual = lhsArray == rhsArray

OR

let isEqual = lhsArray.elementsEqual(rhsArray, by: { $0 == $1} )

Method 2 (Without Equatable Protocol)

Step 1 - Sort Array as described in Method1, step 2

Step 2 - Use elementsEqual

lhsArray.elementsEqual(rhsArray, by: { $0.identifier == $1.identifier })

Read more about Array Comparison here

How to compare two arrays in JavaScript?, In Javascript, to compare two arrays we need to check that the length of both arrays should be same, the objects present in it are of the same type and each item  If the two arrays are considered equal both arrays contain the same number of elements, and all pairs of elements in the two arrays are equal use Arrays.equals. If two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal use Arrays.deepEquals .

First we extend Equatable class, to have a DRY code, than if the 2 arrays are always of the same size, or if at least the first one is <= than the second you can go with this solution.

Pay attention that you are working with optionals, you may have to unwrap them before.

class A {
    var identifier: String?
    var quantity: Int = 0

    init(identifier: String, quantity: Int) {
        self.identifier = identifier
        self.quantity = quantity
    }
}

let a1: A = A(identifier: "1", quantity: 1)
let a2: A = A(identifier: "2", quantity: 2)
let a3: A = A(identifier: "3", quantity: 3)
let a4: A = A(identifier: "4", quantity: 4)

let a5: A = A(identifier: "1", quantity: 1)
let a6: A = A(identifier: "2", quantity: 2)
let a7: A = A(identifier: "3", quantity: 3)
let a8: A = A(identifier: "4", quantity: 4)

var array1: [A] = [a1, a2, a3, a4]
var array2: [A] = [a5, a6, a7, a8]

func areEquals(array1: [A], array2: [A]) -> Bool {
    if array1.count < array2.count {
        return false
    }
    for i in 0...array2.count - 1 {
        if array1[i] != array2[i] {
            return false
        }
    }
    return true
}


extension A: Equatable {
    static func ==(lhs: A, rhs: A) -> Bool {
        //you can choose how and when they should be equals
        return lhs.identifier == rhs.identifier
    }
}

How to compare two arrays in Java?, equals() to compare two arrays. Actually, there is a list of equals() methods in Arrays class for different primitive types (int, char, ..etc) and one for Object  Few things to note though, it won’t work with nested objects and the order of the keys are important. The idea behind this is similar to the stringify way. It coverts the object into a string and compare if the strings are a match. Essentially it's comparing the equality of two strings. That's why the order matters.

try this code, let me know if it works

func toDictionary<E, K, V>(
    array:       [E],
    transformer: (element: E) -> (key: K, value: V)?)
    -> Dictionary<K, V>
{
    return array.reduce([:]) {
        (var dict, e) in
        if let (key, value) = transformer(element: e)
        {
            dict[key] = value
        }
        return dict
    }
}

then you can execute a check like below

let areEqual = array1.count == array2.count;
if areEqual {
    let dict1 = toDictionary(array1) { ($0.identifier, $0.quantity) }
    let dict2 = toDictionary(array2) { ($0.identifier, $0.quantity) }
    areEqual = NSDictionary(dictionary: dict1).isEqualToDictionary(dict2)
}
print(areEqual)

disclaimer: function toDictionary has been took form here

Comparing two arrays to see if they contain objects with different IDs , function areDifferentByIds(a, b) { var idsA = a.map( function(x){ return x.id; } ).​unique().sort(); var idsB = b.map( function(x){ return x.id; } ).unique().sort(); return​  Using Compare-Object You can see below that the Compare-Object cmdlet allows you to compare both arrays at once. If the SideIndicator property is =>, this means the InputObject property returned is in the DifferenceObject value and not in the ReferenceObject value and vice versa for the <= SideIndicator.

Comparison of Two arrays Using JavaScript, Comparison of arrays by using forEach method. This question is most commonly asked in interviews. There are different ways to achieve these,  Have you considered using a HashMap (or LinkedHashMap) instead of an Array. This way you can use the productId as the key and the product as the value? This will let you get the object without having to loop through the entire array.

How to compare two JavaScript array objects using JavaScript?, In this article, we will see how we can compare two JavaScript array objects using JavaScript? How to compare array contents? A simple way is to run a loop and compare elements one by one. Java provides a direct method Arrays.equals() to compare two arrays. Actually, there is a list of equals() methods in Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is base of all classes in Java).

EXP02-J. Do not use the Object.equals() method to compare two , equals() on any array compares only array references, not their contents. Programmers who wish to compare the contents of two arrays must use the static two-  Step 1: We need to declare the function with two parameters. function compare(arr1,arr2){} Step 2: We need to Initialize an empty array. function compare(arr1,arr2){const finalarray =[];} Step 3: We are taking the help of forEach method in Array.protoype.forEach().

Comments
  • array1 and array2 will always be of the same size? show array count be a check also? or check should be on properties of each element in arrays?
  • @ddb: sorry, their counts are random
  • so if they have different counts, they should be classified as unequal, right?
  • What do you consider equal? If they have the same length? If they have the same items? Do the items all have to be at the same index?
  • @ddb: ya... I got it, but how about another case @-@
  • @Rahul Tripathi, dear Rahul Tripathi can you please explain your code. It's interesting, but I can't understood.This is my code let array1: [Int] = [1, 2, 3, 4] let array2: [Int] = [5, 6, 7, 8] let result = zip(array1, array2).enumerated().filter() { $1.0 == $1.1 }.map{$0.0} print(result)
  • Event if this works, it looks like a copy paste code from somewhere without any explanation of the code!.@Rahul Tripathi
  • I do not think this is a good solution. It only works for one scenario i.e. when the two arrays are sorted in the same sequence.
  • There is no reason to use .enumerate() to get count of the matched items, but then filter will looks like { $0.0.id == $0.1.id }