简体   繁体   中英

javascript : compare content of two array of objects by some id and return true or false

i need a little help to compare two array of objects and look if the array A has the same content of array B by using an id who is inside both arrays, for example:

 example false: ArrayObjectA = [{ id: 1, name: josh, age: 31 },{ id: 2, name: Kyle, age: 21}]; ArrayObjectB = [{ id: 1, name: josh, age: 31 }]; ArrayObjectB content is equals to ArrayObjectA => false example true: ArrayObjectA = [{ id: 1, name: josh, age: 31 },{ id: 2, name: Kyle, age: 21}]; ArrayObjectB = [{ id: 1, name: josh, age: 31 },{ id: 2, name: Kyle, age: 21}]; ArrayObjectB content is equals to ArrayObjectA => true

i found a library called lodash but i dont know if is useful.

any help is appreciated.

We can get ids list from each array and check if all elements are equal

const compareArrays = (arr1, arr2) => {
  const ids1 = arr1.map(v => v.id).sort() 
  const ids2 = arr2.map(v => v.id).sort()

  return ids1.length === ids2.length && ids1.every((v, ind) => v === ids2[ind])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM