js数组对象合并与拆分求助

var arr=[
    {type:1,word:["this"]},
    {type:1,word:["is"]},
    {type:1,word:["my"]},
    {type:0,word:["or"]},
    {type:0,word:["this"]},
    {type:4,word:["aaa"]},
    {type:4,word:["bbb"]},
    {type:4,word:["ccc"]},
]

一:type不等于0的合并为(不挨在一起不可以合并)

arr=[
    {type:1,word:["this","is","my"]},,
    {type:0,word:["or"]},
    {type:0,word:["this"]},
    {type:4,word:["aaa","bbb","ccc]},
    {type:1,word:["wei"]},
]

二:将一的type等于1的变为0后数组变成(这相当于有个按钮,取消选中,然后将一的结果变为二)

arr=[
    {type:0,word:["this"]},
    {type:0,word:["is"]},
    {type:0,word:["my"]},
    {type:0,word:["or"]},
    {type:0,word:["this"]},
    {type:4,word:["aaa","bbb","ccc]},
    {type:1,word:["wei"]},
]

下面是我项目需求图片(可以不看)
图片说明


图片说明

/**
         * @param {number[][]} list
         * @param {number} k
         * @return {number}
         */
        var kthSmallest = function (list, k) {
            // k 为1:type不等于0的合并为(不挨在一起不可以合并)
            // k 为2:将一的type等于1的变为0后数组变成

            // 因为会多次调用,直接修改传进来的数组可能会影响到下次调用,则需要声明一个数组来作为基准数组
            let arr = JSON.parse(JSON.stringify(list));
            let _result = [];
            let len = arr.length, i = 0;
            if (k === 1) {
                while (i < len) {
                    // 指针在当前这个arr元素中,此时结果数组的长度,用户比较这个子集的type是不是和上面一个一样即碍着
                    let resultLen = _result.length;
                    if (arr[i].type === 0 || resultLen === 0) {
                        // 等于0的不合并,直接放到数组最后面
                        // 第一个元素也直接放入
                        _result.push(arr[i])
                    } else if (_result[resultLen - 1].type === arr[i].type) {
                        // 如果挨在一起合并word
                        arr[i].word.forEach(i => _result[resultLen - 1].word.push(i));
                    } else {
                        // 不属于上面的情况,直接放到数组最后面
                        _result.push(arr[i])
                    }
                    i++
                }
            } else {
                _result = arr.map(i => {
                    i.type === 1 ? i.type = 0 : i
                    return i
                })
            }
            return _result

        };

var arr = [
{ type: 1, word: ["this"] },
{ type: 1, word: ["is"] },
{ type: 1, word: ["my"] },
{ type: 0, word: ["or"] },
{ type: 0, word: ["this"] },
{ type: 4, word: ["aaa"] },
{ type: 4, word: ["bbb"] },
{ type: 4, word: ["ccc"] },
];
console.log(kthSmallest(arr, 1)
console.log(kthSmallest(arr, 2))

    不知道上面的逻辑是不是你想要的,另外按照我理解的,感觉这个逻辑其实不是很难呢,哈哈哈,如果有问题请给我留言
    另外,不好意思借机推下自己的公众号:**坑人的小书童**,哈哈哈 ,每天更新一道算法题,感兴趣可以一块坚持学习哦