0
var list1 = ["pms","lms","nms","qsf"];

var list2 = ["pms","SSS","lms"];

How do I compare list2 with list1 of arrays items and throw an error if any one of list2 item doesn't match with list1.

I know it may be a simple question but I am from different background and not so good in Javascript.

John Seen
  • 701
  • 4
  • 15
  • 31
  • You have to take the intersection of arrays. See this http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript – abhishekkannojia Jun 23 '16 at 12:43
  • Possible duplicate of [How to compare arrays in JavaScript?](http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – TimoStaudinger Jun 23 '16 at 12:45

3 Answers3

0

You can create a map for list2 first

var lookupMap = {}

list2.forEach(function(value){
lookupMap[value] = 1;
});

// now iterate list1
list1.forEach(function(value){
if (!lookupMap[value]) {
//throw error
}
});
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
0

You can use every() which returns true/false if all elements in the array pass the test in function.

var list1 = ["pms", "lms", "nms", "qsf"];
var list2 = ["pms", "SSS", "lms"];

var result = list2.every(function(e) {
  return list1.indexOf(e) != -1;
})

console.log(result)

With ES6 you can do same thing like this

var list1 = ["pms","lms","nms","qsf"], list2 = ["pms","SSS","lms"];

var result = list2.every((e) => list1.includes(e));
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

I might do like this

var list1 = ["pms","lms","nms","qsf"],
    list2 = ["pms","SSS","lms"],
     pass = list2.every(e => list1.some(f => f == e));
     console.log(pass); // false
Redu
  • 25,060
  • 6
  • 56
  • 76