1

How do i check each element of one array into another? here array2 contains each element of array1.

code:

function find(a, b) {
     var ai=0, bi=0;
  var result = [];

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  if(JSON.stringify(a)==JSON.stringify(result)){
    return true;
  }else if(JSON.stringify(b)==JSON.stringify(result)){
    return true;
  }else{
    return false;
  }
  // return result;

}

var array1 =  ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"];
var array2 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"];

console.log(find(array1, array2)); //returns false
console.log(find(array2, array1)); // return false
Juned Ansari
  • 5,035
  • 7
  • 56
  • 89

3 Answers3

2

If you want to check every value one by one you can use map and includes to check if the array contains any value from array1

var array1 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"];
var array2 = ["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"];

array1.map(x => console.log(array2.includes(x)))
PEPEGA
  • 2,214
  • 20
  • 37
  • `for`-solution that was previously accepted has performance advantage over that one as it will exit upon hitting missing element. Though you may benefit from both high order syntax conciseness and shortcut flexibility with [`Array.prototype.every()`](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/every) as it is done in my [solution](https://stackoverflow.com/a/59160854/11299053) below. – Yevhen Horbunkov Dec 03 '19 at 16:00
2

String contain white space in the end so make sure you trim it before process it.

ex: Party Address contain white space

function isSuperset(set, subset) {
    for (var elem of subset) {
        if (!set.has(elem)) {
            return false;
        }
    }
    return true;
}


var array1 =  new Set(["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Party Address", "Party Name", "Pincode"].map(el => el.trim()));
var array2 = new Set(["Area", "Code", "Date", "Invoice Amt", "Invoice No", "Name", "Party Address ", "Party Name", "Pincode"].map(el => el.trim()));

let result = isSuperset(array2, array1);
console.log(result);
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0

You can use Array.prototype.includes()

const arr1 = [/* someValues */];
const arr2 = [/* someMoreValues */];

for (let value of arr1) {
    if (arr2.includes(value)) {
        // do stuff
    }
}

you can also use includes() with map()

arr1.map(x => console.log(arr2.includes(x)));
JDunken
  • 465
  • 2
  • 7