前言:
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??
首先数组是利用数组map方法去遍历arr的每一个值,然后进行于newValue的id进行对比,不同返回原来的项,相同返回newValue.
不装逼清晰点写法:
- const updated = arr.map(function(item) {
- return item.id == newValue.id ? newValue: item;
- });
对于大神来说,我有一百种方法处理这个问题。
方案 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 } ]
- //利用es6的 ...运算符将其他属性和a属性分开来,这波操作很亮眼 !
- const obj = {a: 1, b: 2, c: 3};
- const {a, ...newObj} = obj;
- console.log(newObj) // => {b: 2, c: 3};
- //利用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]
- //利用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,欢迎大神的你进行提供更厉害的方法。请在留言区约起来!
来源: http://www.cnblogs.com/mdengcc/p/7614601.html