前言:es6
金秋九月的最後一天,忽然發現這個月博客啥也沒更新,不寫點什麼總以爲這個月沒啥長進,逆水行舟,不進則退,前進的路上貴在堅持,說好的每月至少一到兩篇,不能半途而廢!好多知識寫下來也能加深一下自身的記憶。因此在國慶前一天和你們分享下本身收藏的一些JS 的數組或對象處理或者很是簡單的算法問題。算法
一、根據屬性來更新一個數組中的對象數組
const arr = [ {id: 1, score: 1}, {id: 2, score: 2}, {id: 3, score: 4}];
//更新的值
const newValue = {id: 3, score: 3}
更新數組中id爲3的score值。spa
Es6 裝逼寫法以下:3d
const result = initial.map(x => x.id === newValue.id ? newValue : x); //是否是很裝B??
首先數組是利用數組map方法去遍歷arr的每個值,而後進行於newValue的id進行對比,不一樣返回原來的項,相同返回newValue.code
不裝逼清晰點寫法:對象
const updated = arr.map(function(item){ return item.id == newValue.id ? newValue : item ; });
對於大神來講,我有一百種方法處理這個問題。blog
方案 Arem
// 遍歷數組,創建新數組,利用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,歡迎大神的你進行提供更厲害的方法。請在留言區約起來!
注:本文出自博客園 https://home.cnblogs.com/u/mdengcc/ ,轉載請註明出處。