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和4const 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;}