javascript jquery数组相交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4003496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:08:05  来源:igfitidea点击:

jquery arrays intersect

javascriptjqueryarraysformsintersect

提问by tschardak

I previously posted this question as jquery/javascript: arrays - jquery/javascript: arrays. But since I am a complete beginner I have formulated the question wrong and didn't understand the answers either.... :(

我之前将这个问题发布为 jquery/javascript: arrays - jquery/javascript: arrays。但由于我是一个完整的初学者,我把问题表述错了,也不明白答案...... :(

After failing to implement the given solutions I did some more looking around I found out that I need to compare 6 arrays of possible choices and intersect them to finally display only the overlapping values.

在未能实现给定的解决方案后,我又环顾四周,发现我需要比较 6 个可能选择的数组并将它们相交以最终仅显示重叠值。

So this is, hopely, a clearer formulation:

所以,希望这是一个更清晰的表述:

I have 6 questions/6 groups of radio buttons for answers. Each answer has multiple values (they can range from 1 to 38 items to be displayed in final 'advice'). I am collecting the values of checked radios in arrays. I get 6 arrays.

我有 6 个问题/6 组单选按钮供回答。每个答案都有多个值(它们可以从 1 到 38 个项目显示在最终的“建议”中)。我正在收集数组中已检查无线电的值。我得到 6 个数组。

How do I intersect 6 arrays in order to get one final array containing only intersecting values form all 6 choices? How do I turn items of this final array into selectors?

如何将 6 个数组相交以获得一个仅包含所有 6 个选择的相交值的最终数组?如何将这个最终数组的项目转换为选择器?

Can someone please help me? Thank you!

有人可以帮帮我吗?谢谢!

My script looks now like:

我的脚本现在看起来像:

(function($){
  $.fn.checkboxval = function(){
      var outArr = [];
      this.filter(':checked').each(function(){
            outArr.push(this.getAttribute("value"));
      });
      return outArr;
  };
})
(jQuery);
$(function(){
  $('#link').click(function(){
    var valArr1 = $('#vraag1 input:radio:checked').checkboxval();
    var valArr2 = $('#vraag2 input:radio:checked').checkboxval();
    var valArr3 = $('#vraag3 input:radio:checked').checkboxval();
    var valArr4 = $('#vraag4 input:radio:checked').checkboxval();
    var valArr5 = $('#vraag5 input:radio:checked').checkboxval();
    var valArr6 = $('#vraag6 input:radio:checked').checkboxval();
// var newArray = $.merge(valArr1, valArr2, valArr3, valArr4, valArr5, valArr6); <- test to see if I can merge them
// $('#output').text(newArray.join(',')); <- test to see if I can join them
//$("#output").html($("#output").html().replace(/,/gi, ',#diet')); <- test to see if I can append text so it looks like the selectors of divs I need to display later
//    return false;
  });
});

my form/inputs looks like:

我的表单/输入看起来像:

<input name="vraag1" type="radio" value="1a,4,5,12,13,17a,18,19,22,23,24,26,27,28,29,30,33,38,6" class="radio advice" id="vraag1-0" /><label for="vraag1-0">ja</label>
<br />
<input name="vraag1" type="radio" value="1b,1,2,3,7,8,11,9,14,15,16,17,20,21,25,31,34,35,36,37,10,32" class="radio advice" id="vraag1-1" /><label for="vraag1-1">nee</label>
<br />
<input name="vraag1" type="radio" value="1c,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,17a,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38" class="radio advice" id="vraag1-2" /><label for="vraag1-2">maakt mij niet uit</label>

采纳答案by Mottie

Your question is still very confusing to me.

你的问题还是让我很困惑。

But it appears you are getting the value from the inputs and trying to combine them. But they are all strings not arrays.

但看起来您正在从输入中获取价值并尝试将它们组合起来。但它们都是字符串而不是数组。

Try just adding the strings together, then breaking them apart using split()(demo)

尝试将字符串加在一起,然后使用split()演示)将它们分开

$('#link').click(function() {
    var radios = '';
    $('input:radio:checked').each(function() {
        radios += $(this).val() + ',';
    })
    // remove last comma & convert to array
    radios = radios.substring(0, radios.length - 1).split(',');
    // do something with the array
    console.debug(radios);
})


Update: Ok, from your demo HTML, I couldn't get 6 duplicates so in the demo I set it to find 3+ matches. I had to write this script to find duplicates in an array I also made it to return an associative object with the number of duplicates. There may be a better method, but this is what I came up with (updated demo):

更新:好的,从您的演示 HTML 中,我无法获得 6 个重复项,因此在演示中我将其设置为查找 3 个以上的匹配项。我必须编写这个脚本来查找数组中的重复项 我还让它返回一个具有重复项数的关联对象。可能有更好的方法,但这是我想出的(更新的演示):

$(function() {
    $('#link').click(function() {
        var radios = '';
        $('input:radio:checked').each(function() {
            radios += $(this).val() + ',';
        })
        // remove last comma & convert to array
        var results = [],
            dupes = radios
             .substring(0, radios.length - 1)
             .split(',')
             .getDuplicates(),
            arr = dupes[0],
            arrobj = dupes[1],
            minimumDuplicates = 6; // Change this to set minimum # of dupes to find

        // find duplicates with the minimum # required
        for (var i=0; i < arr.length; i++){
            if ( arrobj[arr[i]] >= minimumDuplicates ){
                results.push(arr[i]);
            }
        }

        // Show id of results
        var diets = $.map(results, function(n,i){ return '#diet' + n; }).join(',');
        $(diets).show(); // you can also slideDown() or fadeIn() here
    })
});


/* Find & return only duplicates from an Array
 * also returned is an object with the # of duplicates found
 * myArray = ["ccc", "aaa", "bbb", "aaa", "aaa", "aaa", "aaa", "bbb"];
 * x = myArray.getDuplicates();
 * // x = [ array of duplicates, associative object with # found]
 * // x = [ ['aaa','bbb'] , { 'aaa' : 5, 'bbb' : 2 } ]
 * alert(x[0]) // x[0] = ['aaa','bbb'] & alerts aaa,bbb
 * alert(x[1]['aaa']) // alerts 5;
 */
Array.prototype.getDuplicates = function(sort) {
    var u = {}, a = [], b = {}, c, i, l = this.length;
    for (i = 0; i < l; ++i) {
        c = this[i];
        if (c in u) {
            if (c in b) { b[c] += 1; } else { a.push(c); b[c] = 2; }
        }
        u[c] = 1;
    }
    // return array and associative array with # found
    return (sort) ? [a.sort(), b] : [a, b];
}

回答by user982671

With jQuery loaded, you can punch in the console:

加载 jQuery 后,您可以在控制台中输入:

a1=[1,2,3]
a2=[2,3,4,5]
$.map(a1,function(a){return $.inArray(a, a2) < 0 ? null : a;})

The output should be:

输出应该是:

[2, 3]

回答by Christoph

Was just wondering the same thing and came up with this:

只是想知道同样的事情并想出了这个:

$(["a","b"]).filter(["a","c"])

returns

回报

["a"]

回答by Kristian Abrahamsen

If yoou want do do an intersect operation on arrays you can use the jQuery plugin jQuery Array Utilities

如果你想对数组做一个相交操作,你可以使用 jQuery 插件jQuery Array Utilities

Here is an example code line of how to use it:

这是如何使用它的示例代码行:

$.intersect([1, 2, 2, 3], [2, 3, 4, 5, 5])

will return the result [2,3]

将返回结果 [2,3]

回答by StanleyH

See Simplest code for array intersection in javascriptfor an intersection function. Split the strings with split(",") and do an intersection on the resulting arrays of strings.

有关交集函数,请参阅JavaScript 中数组交集的最简单代码。使用 split(",") 拆分字符串并对结果的字符串数组进行交集。

回答by Czika István

function intersect(a, b) {
    var aIsShorter = a.length < b.length;
    var shorter = aIsShorter ? a : b;
    var longer = aIsShorter ? b : a;

    return longer.filter(isFoundInOther).filter(isFoundOnce);

    function isFoundInOther(e) {
        return shorter.indexOf(e) !== -1;
    }

    function isFoundOnce(element, index, array) {
        return array.indexOf(element) === index;
    }
}