0

I tried something like:

var diff = $(array1).not(array2).get();
console.log(diff); // store the difference

And replace .not() with .is() but that didn't work..which generated an error. It only stored the difference, but I want only the same values stored in a new array. How do I do that in jQuery regardless if it's length size in both arrays?

var array1 = ['a','b','c','d','e','f','g'];
var array2 = ['c', 'b'];
var sameValArr = [];

// TODO:
// 1. compare the two arrays if there's any matching values in both
// 2. if yes, store the matching value in a new array; if no, do nothing
// 3. check the new array if it isn't empty 
// 4. if empty, hide the video; if not empty do nothing (show video)

    for(var i = 0; i < array1.length; i++)
    {
        for(var j = 0; j < array2.length; j++)
        {
            if(array1.indexOf([i]) === array2.indexOf([j]))
            {
               sameValArr.push(array1[i]);
                console.log("sameValArr: ", sameValArr);
            }      
        }
    }

The answer provided to this question using indexOf() method didn't work.

TheAmazingKnight
  • 2,442
  • 9
  • 49
  • 77

1 Answers1

0
for(var i=0; i< array1.length; i++)
{
    for(var j=0; j< array2.length; j++)
    {
        if(array1[i] === array2[j])
            sameValArr.push(array1[i]);
    }
{
Kevin Grosgojat
  • 1,386
  • 8
  • 13
  • This doesn't account for if the values are attached to different key locations/positions. IndexOf actually searches through and checks if its in the array at all. – Ukuser32 Mar 15 '16 at 15:42
  • Tried your answer along with indexOf() but didn't work. – TheAmazingKnight Mar 15 '16 at 15:53
  • My solution give you an array of the values that are presents in the 2 arrays. What would you do after ? – Kevin Grosgojat Mar 15 '16 at 16:05
  • While this answer is probably correct and useful, it is preferred if you [include some explanation along with it](http://meta.stackexchange.com/q/114762/159034) to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. Thanks! – Hatchet Mar 15 '16 at 18:04