前言:
金秋九月的最后一天,突然发现这个月博客啥也没更新,不写点什么总觉得这个月没啥长进,逆水行舟,不进则退,前进的路上贵在坚持,说好的每个月至少一到两篇,不能半途而废!好多知识写下来也能加深一下自身的记忆。所以在国庆前一天和大家分享下自己收藏的一些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 } ]对于大神来说,我有一百种方法处理这个问题。
方案 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种方案。
同理这样是可以去出一个数组中指定的元素
//去掉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]感觉这个方法不够装B,欢迎大神的你进行提供更厉害的方法。请在留言区约起来!
注:本文出自博客园 https://home.cnblogs.com/u/mdengcc/ ,转载请注明出处。
转载于:https://www.cnblogs.com/mdengcc/p/7614601.html
相关资源:JAVA上百实例源码以及开源项目