compare items in array javascript code example

Example 1: javascript compare arrays

Array.prototype.equals = function(arr2) {
  return (
    this.length === arr2.length &&
    this.every((value, index) => value === arr2[index])
  );
};

[1, 2, 3].equals([1, 2, 3]);	// true
[1, 2, 3].equals([3, 6, 4, 2]);	// false

Example 2: comparing array of objects in javascript

// IN THIS EXAMPLE WE HAVE GROUP INSERTS - DATA TO BE ADDED TO DB
// TO INSERT INTO DB EACH GROUP NAME MUST BE THE MATCHING ID
// CONATCT NAME MUST ALSO BE MATCHING ID
// THE CODE BELOW SHOWS HOW TO TRAVERSE THROGUH TWO ARRAYS AND COMPARE / ADD VALES

const groupInserts = [ { groups: [ 'Chess', 'Science', 'German' ], name: 'Ian Smith' },
  { groups: [ 'Swimming' ], name: 'Jenny Smith' },
  { groups: [ 'Tennis' ], name: 'Susan Jones' },
  { groups: [ 'Coding', 'Science' ], name: 'Judy Davis' } ]

const nameAndIdsFromDB = [ { name: 'Parent_1', id: 1 },
{ name: 'Parent_2', id: 2 },
{ name: 'Ian Smith', id: 99 },
{ name: 'Jenny Smith', id: 100 },
{ name: 'Susan Jones', id: 101 },
{ name: 'Judy Davis', id: 102 } ]

const groupnameAndIdsFromDB = [ { name: 'Debugging', id: 1 },
{ name: 'React', id: 2 },
{ name: 'New record with no people', id: 3 },
{ name: 'New record with people', id: 4 },
{ name: 'Chess', id: 12 },
{ name: 'Science', id: 13 },
{ name: 'German', id: 14 },
{ name: 'Swimming', id: 15 },
{ name: 'Tennis', id: 16 },
{ name: 'Coding', id: 17 } ]

let groupNamesWithIds = [];
groupInserts.forEach(data => {
    if (data.groups) {
         data.groups.map(e => {
                let obj = {};
                obj.group = e;
                obj.name = data.name
                groupNamesWithIds.push(obj);
        })
    }
})


let addedMessageGroupIds = [];
groupNamesWithIds.forEach(data => {
  groupnameAndIdsFromDB.map(e => {
    if (e.name === data.group) {
      addedMessageGroupIds.push({group: data.group, name: data.name, messages_individual_groups_id: e.id})
    }
  })
})

let addedContactIds = [];
addedMessageGroupIds.forEach(data => {
  nameAndIdsFromDB.map(e => {
    if (e.name === data.name) {
      addedContactIds.push({messages_individual_groups_id: data.messages_individual_groups_id, contact_id: e.id, created_at: Date.now()})
    }
  })
})

Example 3: compare arrays javascript

// For regular 1D array
const array1 = [1,2,3,4]
const array2 = [1,2,3,4]

array1.join() === array2.join()
// '1,2,3,4' === '1,2,3,4'

// For anything more complex
const array3 = [1,2,3,[1,2,3]]
const array4 = [1,2,3,[1,2,3]]

JSON.stringify(array3) === JSON.stringify(array4)