根据属性顺序将数组拆分为块

时间:2017-08-25 10:31:02

标签: javascript arrays

有一个包含对象的数组。

看起来像这样:

[{id:2},{id:3},{id:4},{id:9},{id:10},{id:11}]

结果我想要这个:

[{id:2,id:4},{id:9,id:11}]

不知道如何删除中间值(正则它们是连续的),以及当我们没有id时如何将它分成组:5,6,7,8,这意味着有序列中的差距。

3 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望将输入拆分为每个部分具有RFC 3489/5389/5766/5780/6062/6156 STUN/TURN Server Version Coturn-4.5.0.6 'dan Eider' 0: Max number of open files/sockets allowed for this process: 8191 0: Due to the open files/sockets limitation, max supported number of TURN Sessions possible is: 4000 (approximately) 0: ==== Show him the instruments, Practical Frost: ==== 0: TLS supported 0: DTLS supported 0: DTLS 1.2 supported 0: TURN/STUN ALPN supported 0: Third-party authorization (oAuth) supported 0: GCM (AEAD) supported 0: OpenSSL compile-time version: OpenSSL 1.1.0f 25 May 2017 (0x1010006f) 0: 0: SQLite supported, default database location is /usr/local/var/db/turndb 0: Redis is not supported 0: PostgreSQL is not supported 0: MySQL supported 0: MongoDB is not supported 0: 0: Default Net Engine version: 1 (UDP listening socket per session) 值连续的对象的部分,然后仅在每个部分中包含该序列的第一个和最后一个对象。

你可以这样做:



id

var input = [{id:2},{id:3},{id:4},{id:9},{id:10},{id:11},{id:15},{id:16},{id:17},];

var result = input.reduce ( (acc, obj, i) => {
    if (i && input[i-1].id === obj.id - 1) {
        acc.last[1] = obj;
    } else {
        acc.push(acc.last = [obj]);
    }
    return acc;
}, []);

console.log(result);




答案 1 :(得分:0)


如果符合条件,您可以遍历数组并将对象添加到新数组中。

var arrNew = [];
for(int i=0;i<arr.length;i++){
    var obj = arr[i];
    if(obj.id ==2 || obj.id==100){
        conitnue;
    }
    arrNew.push(obj);
}

答案 2 :(得分:0)

您可以按id对其进行分组,并选择不同的键以留下正确的属性。

&#13;
&#13;
var array = [{ id: 2 }, { id: 3 }, { id: 4 }, { id: 9 }, { id: 10 }, { id: 11 }],
    result = array
        .reduce(function (r, a) {
            var last = r[r.length - 1];
            if (last && last.right + 1 === a.id) {
                last.right = a.id;
            } else {
                r.push({ left: a.id, right: a.id });
            }
            return r;
        }, []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;