zoukankan      html  css  js  c++  java
  • 去掉数组或者字符串中相邻的重复数据

    题目来源:https://www.codewars.com/kata/54e6533c92449cc251001667/train/javascript

    有参考:https://www.jianshu.com/p/cae3daf4b310

    题目内容:

    Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

    For example:

    uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
    uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
    uniqueInOrder([1,2,2,3,3]) == [1,2,3]

    自己的答案:

    var uniqueInOrder=function(val){
      if (typeof val === 'string') {
        arr = val.split('');
      } else {
        arr = val;
      }
      if (arr.length === 0) return [];
      let preItem = arr[0];
      const result = [arr[0]];
      const add = arr.filter(item => {
        if (item === preItem) return false;
        preItem = item;
        return true;
      });
      return result.concat(add);
    }
    

    很笨拙的方法。提交以后看到一个很牛的答案:

    var uniqueInOrder=function(iterable){
        return [...iterable].filter((a, i) => a !== iterable[i-1])
    }
    

    之后去看了一下扩展运算符的用法。
    参考:https://blog.csdn.net/qq_30100043/article/details/53391308

    const func=(val)=>{
      console.log([...val]);
    };
      
    func('hfwioe');     //如果传进去的参数是个字符串
    // 输出结果: ["h", "f", "w", "i", "o", "e"]
    
    func(['a','b','c']);    //如果传进去的参数是个数组
    // 输出结果: ["a", "b", "c"]
    

    1.用于合并数组

    // ES5
    [1, 2].concat(more)
    // ES6
    [1, 2, ...more]
    
    var arr1 = ['a', 'b'];
    var arr2 = ['c'];
    var arr3 = ['d', 'e'];
    
    // ES5 数组合并
    arr1.concat(arr2, arr3);
    // [ 'a', 'b', 'c', 'd', 'e' ]
    // ES6 数组合并
    [...arr1, ...arr2, ...arr3]
    // [ 'a', 'b', 'c', 'd', 'e' ]
    

    2.用于解构赋值

    const [first, second,...rest] = [1, 2, 3, 4, 5];
    console.log(first,second,rest);
    // 打印结果: 1 2 [3, 4, 5]
    
  • 相关阅读:
    嵌入式Linux系统的构成和启动过程
    Linux 设备驱动之字符设备
    Linux的inode的理解
    flannel流程解析
    http2协议的理解
    多线程和单线程的理解
    User Token简单总结
    前端组件开发方法论
    Electron踩坑记录
    2020年工作总结
  • 原文地址:https://www.cnblogs.com/hikki-station/p/13750495.html
Copyright © 2011-2022 走看看