-2

I have a situation where i want to check if elements in one array are present in another array. If elements are present, then push those in new array. In this case, i have array of strings.

For e.g.

var check = ["6003", "6005", "6010"]; //static values. I need to check these elements if they are present in InputValues

var InputValues = ["5005", 2005", "6010"]; //dynamic input values

var result = ["6010"]; //dyanimic final array based off elements in InputValues

Similary,

var InputValues = ["5005", 6005", "6010"];

var result = ["6005", "6010"];

Can someone please let me know how to achieve this dynamic result.

user3019647
  • 133
  • 3
  • 13
  • 1
    Probably a duplicate somewhere... but you can do `var set = new Set(check); var result = InputValues.filter(value => set.has(value));` – Patrick Roberts Mar 30 '20 at 01:27
  • [This answer](https://stackoverflow.com/a/37041756/1541563) seems very similar to my suggestion above, but also removes duplicates from both the input arrays before applying the filter. – Patrick Roberts Mar 30 '20 at 01:38

2 Answers2

2
var result = InputValues.filter((val) => check.includes(val));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility

edit: Used the wrong method! .includes() works if you do not care about IE (though it is in Edge), otherwise this is the "modern" on to use :-)

Rycochet
  • 2,860
  • 1
  • 22
  • 39
  • Yep - doh! Though gave an excuse to link to MDN for browser compatibility ;-) – Rycochet Mar 30 '20 at 01:42
  • You still called it `.contains()` in the following paragraph. And no, I would not call this the "modern" one to use. It's more semantic than `.indexOf(...) >= 0` but I would argue that using a `Set` and a `.has()` check like in my comment on the question would be an order of magnitude more efficient, because `.has()` is average O(1) time complexity while `.includes()` is O(n) time complexity. – Patrick Roberts Mar 30 '20 at 01:49
  • Doh - I have no excuse beyond tiredness for that! Changing it into a `Set` and using that may be quicker depending on the length of the array, but unless you're caching the `Set` it's going to be significantly worse for the GC and overall performance - and given the simplicity of the question it's adding a whole lot of things that the OP will probably not understand! ;-) – Rycochet Mar 30 '20 at 07:59
1

You can use Array.indexOf with Array.filter

var result = InputValues.filter(elem => check.indexOf(elem) >= 0);

Basically what it does is, it will filter the elements of InputValues against check case-sensitive wise.

choz
  • 17,242
  • 4
  • 53
  • 73