Finding A - B from two arrays using underscore.js

半世苍凉 提交于 2019-12-13 14:09:28

问题


I have to filter out certain elements from an array in javascript and thought of using underscore.js for this purpose. As I am new to it,some help is appreciated.Please refer the code below , I have to find A \ B and assign the result to C . Does underscore.js has any convinience method to do that ?

function testUnderScore(){
    alert("underscore test");
    var a = [84, 99, 91, 65, 87, 55, 72, 68, 95, 42];
    var b = [ 87, 55, 72,42 ,13];
    var c = [];

    alert(c);
}

回答1:


By using difference method:

var c = _.difference(a, b);

http://documentcloud.github.com/underscore/#difference




回答2:


I have to find A- B and assign the result to C . Does underscore.js has any convinience method to do that ?

Yes, you can use difference [View Docs] method:

var c = _.difference(a, b);



回答3:


How about:

var a = [1, 2, 5, 6], b = [6], c;

c = a.filter(
    function (aItem) {
        return !(~b.indexOf(aItem));
    }
);

console.log(c);

​ ​



来源:https://stackoverflow.com/questions/10070739/finding-a-b-from-two-arrays-using-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!