Javascript filter array by data from another

后端 未结 7 1595
滥情空心
滥情空心 2020-11-27 22:50

I have an array object:

[
    { id:1, name: \'Pedro\'},
    { id:2, name: \'Miko\'},
    { id:3, name: \'Bear\'},
    { id:4, name: \'Teddy\'},
    { id:5, n         


        
7条回答
  •  -上瘾入骨i
    2020-11-27 23:21

    Maybe take a Array.prototype.reduce in combination with an Array.prototype.some. This keeps the order of the given array need.

    var data = [
            { id: 3, name: 'Bear' },
            { id: 4, name: 'Teddy' },
            { id: 5, name: 'Mouse' },
            { id: 1, name: 'Pedro' },
            { id: 2, name: 'Miko' },
        ],
        need = [1, 3, 5],
        filtered = need.reduce(function (r, a) {
            data.some(function (el) {
                return a === el.id && r.push(el);
            });
            return r;
        }, []);
    
    document.write('
    ' + JSON.stringify(filtered, 0, 4) + '
    ');

    To keep the order of data you can use Array.prototype.filter:

    var data = [
            { id: 3, name: 'Bear' },
            { id: 4, name: 'Teddy' },
            { id: 5, name: 'Mouse' },
            { id: 1, name: 'Pedro' },
            { id: 2, name: 'Miko' },
        ],
        need = [1, 3, 5],
        filtered = data.filter(function (a) {
            return ~need.indexOf(a.id);
        });
    
    document.write('
    ' + JSON.stringify(filtered, 0, 4) + '
    ');

提交回复
热议问题