How to determine whether two arrays are exactly equal?

var arrone = [
        {op: "A", name: "", is_answer: 0, sureid: true},
        {op: "B", name: """, is_answer: 1, sureid: true},
        {op: "C", name: "", is_answer: 1, sureid: true}
   ]
   var arrtwo = [
        {op: "B", name: """, is_answer: 1, sureid: true},
        {op: "C", name: "", is_answer: 1, sureid: true},
        {op: "D", name: "", is_answer: 1}
   ]

how to determine whether the contents of the above two arrays are equal?

Jun.28,2022

// 
function arrayCompare(source, target) {
    return source.length == target.length && source.every((item, index) => item.op == target[index].op)
}
result = arrayCompare(arrone, arrtwo)
console.log(result)

if the string is the same after stringify, then the contents of the two arrays are equal


depends on what your definition of exact equality looks like. if it requires exactly the same, whether in order or for each value, you can serialize both arrays and compare whether the two strings are exactly equal.

if there are some customization requirements, you can only iterate through two arrays and compare them one by one.


you can convert the two arrays into strings and then determine whether they are equal. Use JSON.stringify () or toString ()


loadsh library to introduce this method to try


convert to string comparison


var arrone = [{
            op: "A",
            name: "",
            is_answer: 0,
            sureid: true
        }, {
            op: "B",
            name: """,
            is_answer: 1,
            sureid: true
        }, {
            op: "C",
            name: "",
            is_answer: 1,
            sureid: true
        }]
        var arrtwo = [{
            op: "B",
            name: """,
            is_answer: 1,
            sureid: true
        }, {
            op: "C",
            name: "",
            is_answer: 1,
            sureid: true
        }, {
            op: "D",
            name: "",
            is_answer: 1
        }]

        function isTrue(arr, arr1) {
            if (arr.length !== arr1.length) {
                return false
            }
            for (let i = 0; i < arr.length; iPP) {
                const item = arr[i];
                const item1 = arr1[i];
                if (item['op'] !== item1['op']) {
                    return false
                }
            }
            return true
        }

        console.log(isTrue(arrone, arrtwo))

A library jutils

is encapsulated here.
   

< hr >

I hope I can help you, but I recommend loadsh

.
Menu