如何提取数组中的公共元素分别放到两个数组?

var arr = ["2018-04-17T03", "2018-04-18T15", "2018-04-17T04", "2018-04-18T16", "2018-04-17T05", "2018-04-18T17", "2018-04-17T06", "2018-04-17T07", "2018-04-17T08", "2018-04-17T09", "2018-04-17T20", "2018-04-18T10", "2018-04-17T21", "2018-04-18T11", "2018-04-17T00", "2018-04-17T22", "2018-04-18T12", "2018-04-17T01", "2018-04-17T23", "2018-04-18T13", "2018-04-17T02", "2018-04-18T14", "2018-04-17T14", "2018-04-18T04", "2018-04-17T15", "2018-04-18T05", "2018-04-17T16", "2018-04-18T06", "2018-04-17T17", "2018-04-18T07", "2018-04-17T18", "2018-04-18T08", "2018-04-17T19", "2018-04-18T09", "2018-04-17T10", "2018-04-18T00", "2018-04-17T11", "2018-04-18T01", "2018-04-17T12", "2018-04-18T02", "2018-04-17T13", "2018-04-18T03"];

arr 中的每一个元素后三位不同,我想将每个元素前面十位相同的截取到一个数组,不同的放到另一个数组


墨色风雨
浏览 421回答 2
2回答

一只名叫tom的猫

const arr = ["2018-04-17T03", "2018-04-18T15", "2018-04-17T04", "2018-04-18T16", "2018-04-17T05", "2018-04-18T17", "2018-04-17T06", "2018-04-17T07", "2018-04-17T08", "2018-04-17T09", "2018-04-17T20", "2018-04-18T10", "2018-04-17T21", "2018-04-18T11", "2018-04-17T00", "2018-04-17T22", "2018-04-18T12", "2018-04-17T01", "2018-04-17T23", "2018-04-18T13", "2018-04-17T02", "2018-04-18T14", "2018-04-17T14", "2018-04-18T04", "2018-04-17T15", "2018-04-18T05", "2018-04-17T16", "2018-04-18T06", "2018-04-17T17", "2018-04-18T07", "2018-04-17T18", "2018-04-18T08", "2018-04-17T19", "2018-04-18T09", "2018-04-17T10", "2018-04-18T00", "2018-04-17T11", "2018-04-18T01", "2018-04-17T12", "2018-04-18T02", "2018-04-17T13", "2018-04-18T03"];const prefix = '2018-04-17';  // 这个是相通的前缀,可以换const samePrefix = []; // 存放相同前缀的数组const others = []; // 存放不同前缀的数组arr.forEach(date=>{    if (date.substring(0,10) === prefix) {        samePrefix.push(date)    } else {        others.push(date);    }})

青春有我

var arr = ["2018-04-17T03", "2018-04-18T15", "2018-04-17T04", "2018-04-18T16", "2018-04-17T05", "2018-04-18T17", "2018-04-17T06", "2018-04-17T07", "2018-04-17T08", "2018-04-17T09", "2018-04-17T20", "2018-04-18T10", "2018-04-17T21", "2018-04-18T11", "2018-04-17T00", "2018-04-17T22", "2018-04-18T12", "2018-04-17T01", "2018-04-17T23", "2018-04-18T13", "2018-04-17T02", "2018-04-18T14", "2018-04-17T14", "2018-04-18T04", "2018-04-17T15", "2018-04-18T05", "2018-04-17T16", "2018-04-18T06", "2018-04-17T17", "2018-04-18T07", "2018-04-17T18", "2018-04-18T08", "2018-04-17T19", "2018-04-18T09", "2018-04-17T10", "2018-04-18T00", "2018-04-17T11", "2018-04-18T01", "2018-04-17T12", "2018-04-18T02", "2018-04-17T13", "2018-04-18T03"];    const result=arr.reduce((obj,item)=>{        const key=item.substring(0,10);        if(!obj[key]){            obj[key]=[];        }        obj[key].push(item);        return obj;    },{});    const _result=Object.keys(result).map(key=>result[key]);    console.log(_result);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript