猿问

根据数组里对象属性值是否一致分成二维数组

根据对象里的ym值分成二维数组,比如这种新式
[[{ "date": "2032-10-01", "num": 2, "ym": "203210", "day": "01" },{ "date": "2032-10-01", "num": 2, "ym": "203210", "day": "01" },{ "date": "2032-10-01", "num": 2, "ym": "203210", "day": "01" }],[{ "date": "2032-10-01", "num": 2, "ym": "203211", "day": "01" },{ "date": "2032-10-01", "num": 2, "ym": "203211", "day": "01" }]]

有什么好的方法吗?


月关宝盒
浏览 599回答 3
3回答

白衣染霜花

let data = [{    ym: '1',    id: 1}, {    ym: '2',    id: 2}, {    ym: '1',    id: 3}]function trans (arr) {    let cache = {}    return data.reduce((sum, cur) => {        let index = cache[cur.ym]        if (index !== undefined) {            sum[index].push(cur)        } else {            sum.push([cur])            cache[cur.ym] = sum.length - 1        }        return sum    }, [])}trans(data)

qq_遁去的一_1

var keyArr= [];var jsonArr = [];for(let i in jsonStr){    let str = jsonStr[i];    if(keyArr.include(str.ym)){        let index = keyArr.indexOf(str.ym);        jsonArr.push(str)    }else{        keyArr.push(str.ym);        let index = keyArr.length-1;        jsonArr.push(str)    }    }return jsonArr;

MMMHUHU

const data = [    {ym: 123},    {ym: 345},    {ym: 123},    {ym: 345},]let result = []let subArr = [] // 用于去重(避免同一组ym出现在多个数组中)data.forEach(item1 => {    const ym = item1.ym    if(!subArr.includes(ym)){        subArr.push(ym)        result.push(data.filter(item2 => ym === item2.ym))    }})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答