JS算法(日常积累)

1.给定数组 ["a", "a","a", "c", "c", "t", "a", "a"],输出连续同类项出现次数,输出:["a-3", "c-2", "t-1", "a-2"]

    const arr = ["a", "a","a", "c", "c", "t", "a", "a"];
    let len = arr.length;
    let temp = [];
    let obj = {};
    arr.forEach((e, i)=> {
        if( e !== arr[i-1] && i!==0 ) {
            temp.push(i);
        }
    })
    temp.forEach((e, i)=> {
        arr.splice(e+i, 0, '|')
    })
    let aim = arr.join('').split('|')
    let res = [];
    aim.forEach((e)=> {
        let key = e[0]
        res.push([key]+'-'+e.length);
    })
    console.log(res) // ["a-3", "c-2", "t-1", "a-2"]

 

上一篇:js 中你不知道的各种循环测速


下一篇:C#语法基础08_foreach