最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Finding A - B from two arrays using underscore.js - Stack Overflow

programmeradmin6浏览0评论

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);
}

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);
}
Share Improve this question edited Nov 2, 2018 at 16:15 Novakov 3,0951 gold badge18 silver badges32 bronze badges asked Apr 9, 2012 at 8:29 TitoTito 9,04413 gold badges55 silver badges87 bronze badges 2
  • I just found it out , c= _.without(a, b); will yeild A-B , I will also check the below answers and accept them. – Tito Commented Apr 9, 2012 at 8:35
  • 1 Note: You should better use the proper syntax A \ B in text. – Kijewski Commented Apr 9, 2012 at 8:43
Add a comment  | 

3 Answers 3

Reset to default 20

By using difference method:

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

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

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);

How about:

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

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

console.log(c);

​ ​

发布评论

评论列表(0)

  1. 暂无评论