zoukankan      html  css  js  c++  java
  • JS 数据处理技巧及小算法汇总

      前言:

      金秋九月的最后一天,突然发现这个月博客啥也没更新,不写点什么总觉得这个月没啥长进,逆水行舟,不进则退,前进的路上贵在坚持,说好的每个月至少一到两篇,不能半途而废!好多知识写下来也能加深一下自身的记忆。所以在国庆前一天和大家分享下自己收藏的一些JS 的数组或对象处理或者非常简单的算法问题。

      1、根据属性来更新一个数组中的对象

     const arr = [ {id: 1, score: 1}, {id: 2, score: 2}, {id: 3, score: 4}];
    //更新的值
    const newValue = {id: 3, score: 3}

      更新数组中id为3的score值。

      Es6 装逼写法如下:

    const result = initial.map(x => x.id === newValue.id ? newValue : x); //是不是很装B??
     console.log(updated) // => [ { id: 1, score: 1 }, { id: 2, score: 2 }, { id: 3, score: 3 } ]

      

      首先数组是利用数组map方法去遍历arr的每一个值,然后进行于newValue的id进行对比,不同返回原来的项,相同返回newValue.

      不装逼清晰点写法:

    const updated = arr.map(function(item){
        return item.id == newValue.id ? newValue : item ;
    });
     console.log(updated) // => [ { id: 1, score: 1 }, { id: 2, score: 2 }, { id: 3, score: 3 } ]

       2、数组去重

      对于大神来说,我有一百种方法处理这个问题。

       方案 A

    // 遍历数组,建立新数组,利用indexOf判断是否存在于新数组中,不存在则push到新数组,最后返回新数组 
    function unique(ar) {
        var ret = [];
    
        for (var i = 0, j = ar.length; i < j; i++) {
            if (ret.indexOf(ar[i]) === -1) {
                ret.push(ar[i]);
            }
        }
    
        return ret;
    }

      方案B

    //遍历数组,利用object对象保存数组值,判断数组值是否已经保存在object中,未保存则push到新数组并用object[arrayItem]=1的方式记录保存,这个效率比A高
    function unique(ar) {
        var tmp = {},
            ret = [];
    
        for (var i = 0, j = ar.length; i < j; i++) {
            if (!tmp[ar[i]]) {
                tmp[ar[i]] = 1;
                ret.push(ar[i]);
            }
        }
    
        return ret;
    }

      方案C

    //ES6
    const numbers = [1, 2, 1, 1, 2, 1, 3, 4, 1 ];
    const uniq = [...new Set(numbers)] // => [ 1, 2, 3, 4 ];
    const uniq2 = Array.from(new Set(numbers)) // => [ 1, 2, 3, 4 ];

      稍等,我还有方案D

      方案D

    //filter 
    function unique (arr) {
    var res = arr.filter(function (item, index, array) { return array.indexOf(item) === index; //array.indexOf(item) === index 说明这个元素第一次出现,后面这个item再出现他的item肯定不是index了
    }) return res; }

       欢迎大家留言区给出剩下96种方案。

     

    三、根据属性删除数组中的一个对象

     // 根据属性删除数组中的对象,利用filter进行过滤数组中id相同的项
     const initial = [ {id: 1, score: 1}, {id: 2, score: 2}, {id: 3, score: 4}];
     const removeId = 3;
     const without3 = initial.filter(x => x.id !== removeId);
     console.log(without3) // => [ { id: 1, score: 1 }, { id: 2, score: 2 } ]

    四、删除一个对象上的属性(key)

    //利用es6的 ...运算符将其他属性和a属性分开来,这波操作很亮眼 !
    const
    obj = {a: 1, b: 2, c: 3}; const {a, ...newObj} = obj; console.log(newObj) // => {b: 2, c: 3};


         

    五、两个Set对象相减

    //利用filter对s1进行过滤 ,去掉s2中存在的数字
    const
    s1 = [ 1, 2, 3, 4, 5 ]; const s2 = [ 2, 4 ]; const subtracted = s1.filter(x => s2.indexOf(x) < 0); console.log(subtracted);//[1,3,5]

     同理这样是可以去出一个数组中指定的元素

    //去掉s3中的2和4
     const s3 = [ 1, 2, 3, 4, 5, 4, 5, 6, 2, 2, 4 ];
     const s2 = [ 2, 4 ];
     const subtracted1 = s3.filter(x => s2.indexOf(x) < 0);
    console.log(subtracted1); // [1, 3, 5, 5, 6]

    六、判断一个单词是否是回文

    回文是指把相同的词汇或句子,在下文中调换位置或颠倒过来,产生首尾回环的情趣,叫做回文。例如 12345654321  abcdedbcba 等。
    //利用reverse 进行字符串反转,然后和原字符串对比是否相等
    function isPalindrom(str) {  
        return str == str.split('').reverse().join('');
    }

    七、统计一个字符串出现最多的字母

    //统计每个字母出现的次数,然后存起来,然后进行比较
    function maxTimesChar(str) {
    if(str.length == 1) { return str; } let charObj = {}; for(let i=0;i<str.length;i++) { if(!charObj[str.charAt(i)]) { charObj[str.charAt(i)] = 1; }else{ charObj[str.charAt(i)] += 1; } } let maxChar = '', maxValue = 1; for(var k in charObj) { if(charObj[k] >= maxValue) { maxChar = k; maxValue = charObj[k]; } } return maxChar; }

    感觉这个方法不够装B,欢迎大神的你进行提供更厉害的方法。请在留言区约起来!

    欢迎大家在留言区提供以上问题更优雅的解法,有不同意见或更好的思路欢迎指出,喜欢的话可以点个推荐或者关注( 楼主真不要脸,骗关注 !),最后祝大家国庆愉快!

     

     

     

    注:本文出自博客园 https://home.cnblogs.com/u/mdengcc/ ,转载请注明出处。

     

  • 相关阅读:
    .NET 高效开发之不可错过的实用工具(第一的当然是ReSharper插件)
    灵活运用 SQL SERVER FOR XML PATH 转
    Python 3.X 要使用urllib.request 来抓取网络资源。转
    22-1 拖拽与烟花案例
    21、bootstrap框架
    20、promise与ajax jsonp
    18、MySQL
    19、AJAX
    17、php
    16-1 ECMA5与ECMA6的函数定义
  • 原文地址:https://www.cnblogs.com/mdengcc/p/7614601.html
Copyright © 2011-2022 走看看