A for-loop that compares two arrays looking for matching values

前端 未结 4 883
我在风中等你
我在风中等你 2020-12-14 03:32

I have two arrays that I need to check against each other and if they have reached a point where both items in each array are actually the same as one another, then append s

相关标签:
4条回答
  • 2020-12-14 03:52

    Hi using lodash or underscore you can easily intersection two array.

    _.intersection([2, 1], [2, 3]);

    Result is [2].

    Lodash document: https://lodash.com/docs/4.17.2#intersection

    0 讨论(0)
  • 2020-12-14 04:01

    Here is idea i came up with:

    var daysArray = ["1", "2", "3", "4", "5", "12"];
    var courseHwork = ["4", "8", "15", "16", "23", "42", "12"];
    
    for (var i = 0; i < courseHwork.length; i++) {
        for (var j = 0; j < daysArray.length; j++) {
            if (courseHwork[i] == daysArray[j]) {
              $('div:contains("'+daysArray[j]+'")').append("<div class='assignment'>"+courseHwork[i]+" - appended</div>");
            }
        }
    }
    

    You can find it working here: http://jsfiddle.net/4cqCE/2/

    Well, check if that what you want. First it looks for SAME value in 2 arrays, and if it finds it, it appends something to div containing "4" in it. Is that what you want?

    Here is an example with 2 same values, with 2 divs, each containing one of the value. http://jsfiddle.net/4cqCE/3/

    0 讨论(0)
  • 2020-12-14 04:02

    You can do something like this:

    var daysArray = ["1", "2", "3", "4", "5"];
    var courseHwork = ["4", "8", "15", "16", "23", "42"];
    
    var arr = daysArray.concat(courseHwork);
    var sorted_arr = arr.sort();
    var results = [];
    for (var i = 0; i < arr.length - 1; i++) {
        if (sorted_arr[i + 1] == sorted_arr[i]) {
            results.push(sorted_arr[i]);
        }
    }
    
    console.log(results);
    

    You can run the code here: http://jsfiddle.net/WtEwJ/2/

    This will result in a new array results that only contains the duplicate items.

    0 讨论(0)
  • 2020-12-14 04:12

    i think you should first create an array intersection and then iterate over the result to do your thing...

    0 讨论(0)
提交回复
热议问题