天天看點

22個實用JavaScript程式設計知識,可幫助你提升面試成功率

22個實用JavaScript程式設計知識,可幫助你提升面試成功率

英文 | https://javascript.plainenglish.io/22-utility-functions-to-ace-your-javascript-coding-interview-21ca676ad70

翻譯 | web前端開發公号

你可能會遇到的一種JavaScript面試題,它涉及給定問題編寫1-2行代碼。這些問題通常很容易在5分鐘内回答,但有時由于面試的壓力我們很難解決。今天,我跟你分享的這些功能,将幫助你在面對JavaScript面試題時可以從容應對,同時你也可以将其做為一種參考準備。

為了減輕壓力,面試順利,我們都需要提前做好準備,那就讓我們開始吧!

1、從陣列中删除重複項

數組:這是一些友善的方法,可用于從數組中删除重複項。

1、使用lodash

let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let arrayuniq = _.uniq(array);//[2, 1, 5, 6, 7, 8, 9, 10]      

2、使用filter

let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let list = array.filter((x, i, a) => a.indexOf(x) == i);
//[2, 1, 5, 6, 7, 8, 9, 10]      

3、使用set

let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let setuniq = [...new Set(array)];
//[2, 1, 5, 6, 7, 8, 9, 10]      

2、從對象數組中删除重複項

對象數組:這是一些友善的方法,可用于從對象數組中删除重複項。

1、使用lodash

let users = [
{ id: 1, name: "ted" },
{ id: 1, name: "bob" },
{ id: 3, name: "sara" },
{ id: 4, name: "test" },
{ id: 4, name: "test" },
{ id: 5, name: "abc" }
];
let uniqueUsersByID = _.uniqBy(users, "id");
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]      

我們可以使用此代碼檢查具有多個屬性的唯一資料。

const uniquewithMultipleProperties = _.uniqWith(
    users,
    (a, b) => a.id === b.id || a.name === b.name
);
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]      

2、使用filter

let filteruniquebyID = users.filter(
    (v, i, a) => a.findIndex(t => t.id === v.id) === i
);
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]      

我們可以使用此代碼檢查具有多個屬性的唯一資料。

let filteruniquebyIDName = users.filter(
    (v, i, a) => a.findIndex(t => t.id === v.id || t.name === v.name) === i
);
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]      

3、使用set

var set1 = Array.from(
users.reduce((m, t) => m.set(t.id, t), new Map()).values()
);
//[{"id":1,"name":"bob"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]      

如果你還想了解更多,你可以檢視此位址内容:​​https://st​​ackblitz.com/edit/remove-duplicates-arrayofobjects

3、在數組中查找一個項目

以下是在數組中查找項目的一些方法。

1、includes:此方法确定數組在條目中是否包含某個值,是傳回true值還是false值。

console.log(array.includes(2)); // returns true      

2、 every:此方法測試數組中的所有元素是否通過提供的功能實作的測試。它傳回一個布爾值。

let testevery1 = array.every(val=> val>3); //false      

3、some:此方法測試數組中的至少一個元素是否通過了由提供的函數實作的測試。它傳回一個布爾值。

let testsome1 = array.some(val=> val>3); //true      

4、lodash包括:檢查是否value在中。collection傳回true是否value找到,否則傳回false。

let lodashtest9 =_.includes(array, 1); // true
let lodashtest10 =_.includes(array, 3, 2); // false      

5、findIndex:此方法傳回滿足提供的測試功能的數組中第一個元素的索引。否則,它傳回-1,表明沒有任何元素通過測試。

let  testindex = array.findIndex(val => val > 1);
//0      

6、find:此方法傳回提供的數組中滿足提供的測試功能的第一個元素的值。如果沒有值滿足測試功能,則傳回undefined。

let testfind = array.find(el => (el > 2));
//5      

7、 filter:此方法建立一個新數組,其中所有元素都通過了由提供的功能實作的測試。

let testfilter1 = array.filter(val=> val>3);
//[5, 6, 7, 8, 9, 9, 10]      

8、map:此方法建立一個新數組,其中填充了對調用數組中每個元素調用提供的函數的結果。

let val = [];
array.map(item => { if(item >= 3) val.push(item); });
//[5, 6, 7, 8, 9, 9, 10]      

你可以檢視更多内容:​​https://stackblitz.com/edit/find-item-array​​

4、在對象數組中找到一個項目

這些是可用于在對象數組中查找項目的方法。

1、every:此方法測試數組中的所有元素是否通過提供的功能實作的測試。它傳回一個布爾值。

let testevery2 = users.every(val=> val.id>3);
//false      

2、some:此方法測試數組中的至少一個元素是否通過了提供的功能實作的測試。它傳回一個布爾值。

let testsome2 = users.some(val=> val.id>3); //true      

3、 lodash includes:判斷在collection中傳回的值,如果可以在value找到,則傳回true,否則傳回false。

let lodashtest11 =_.includes({ 'a': 1, 'b': 2 }, 1);
//true
let lodashtest12 =_.includes('abcd', 'bc');
//true      

4、 findIndex:此方法傳回滿足提供的測試功能的數組中第一個元素的索引。否則,它傳回-1,表明沒有任何元素通過測試。

let  testindex2 = users.findIndex(val => val.id > 1);
//3      

5、 find:此方法傳回提供的數組中滿足提供的測試功能的第一個元素的值。如果沒有值滿足測試功能,則傳回undefined。

let testfind2 = users.find(el => (el.id > 2));
//{"id":3,"name":"sara"}      

6、filter:此方法建立一個新數組,其中所有元素都通過了由提供的功能實作的測試。

let testfilter2 = users.filter(val=> val.id>3);      

7、map:此方法建立一個新數組,其中填充了對調用數組中每個元素調用提供的函數的結果。

let val2 = [];
users.map(item => { if(item.id >= 3) val2.push(item); });      

5、對數組項排序

可以使用sort方法對數組進行排序。

該sort()方法對數組中的元素進行适當排序,然後傳回排序後的數組。預設的排序順序是升序,建立在将元素轉換為字元串,然後比較其UTF-16代碼單元值的序列的基礎上。

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]      

6、對具有特定屬性的對象數組進行排序

這些是可以使用對象的特定屬性對對象數組進行排序的方法。

1、簡單排序:此方法對數組中的元素進行适當排序,并傳回排序後的數組。

let data = [{
        id: "3",
        city: "toronto",
        state: "TR",
        zip: "75201",
        price: "123451"
    },
    {
        id: "1",
        city: "anand",
        state: "AN",
        zip: "94210",
        price: "345678"
    },
    {
        id: "5",
        city: "sudbury",
        state: "SB",
        zip: "00110",
        price: "789045"
    }
];
let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id)));console.log("sort test 2 ", sorttest2);
//output
{
    "id": "1",
    "city": "anand",
    "state": "AN",
    "zip": "94210",
    "price": "345678"
}, {
    "id": "3",
    "city": "toronto",
    "state": "TR",
    "zip": "75201",
    "price": "123451"
}, {
    "id": "5",
    "city": "sudbury",
    "state": "SB",
    "zip": "00110",
    "price": "789045"
}]      

2、localCompare:此方法傳回一個數字,該數字訓示參考字元串是按排序順序位于給定字元串之前,之後還是與之相同。

let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id)));
//output
[{
    "id": "1",
    "city": "anand",
    "state": "AN",
    "zip": "94210",
    "price": "345678"
}, {
    "id": "3",
    "city": "toronto",
    "state": "TR",
    "zip": "75201",
    "price": "123451"
}, {
    "id": "5",
    "city": "sudbury",
    "state": "SB",
    "zip": "00110",
    "price": "789045"
}]      

3、用多個字段排序

該parseInt()函數解析一個字元串參數,并傳回一個指定基數的整數(數學數字系統中的基數)。

let sorttest4 = data.sort(function(left, right) {
    var city_order = left.city.localeCompare(right.city);
    var price_order = parseInt(left.price) - parseInt(right.price);
    return city_order || -price_order;
});
//output
[{
    "id": "1",
    "city": "anand",
    "state": "AN",
    "zip": "94210",
    "price": "345678"
}, {
    "id": "5",
    "city": "sudbury",
    "state": "SB",
    "zip": "00110",
    "price": "789045"
}, {
    "id": "3",
    "city": "toronto",
    "state": "TR",
    "zip": "75201",
    "price": "123451"
}]      

4、 Lodash _sortBy:建立一個元素數組,并按照在每個疊代中運作集合中每個元素的結果,以升序排序。

let sorttest6 = _.sortBy(data, ["id", "city"]);
//output
[{
    "id": "1",
    "city": "anand",
    "state": "AN",
    "zip": "94210",
    "price": "345678"
}, {
    "id": "3",
    "city": "toronto",
    "state": "TR",
    "zip": "75201",
    "price": "123451"
}, {
    "id": "5",
    "city": "sudbury",
    "state": "SB",
    "zip": "00110",
    "price": "789045"
}]      

7、對日期數組進行排序

1、使用sort

let isDescending = false; //set to true for Descending
let dates = ["1/7/2021", "1/6/2021", "8/18/2020", "8/6/2020"];
let sorteddates = dates.sort((a, b) => isDescending ? new Date(b).getTime() - new Date(a).getTime() : new Date(a).getTime() - new Date(b).getTime());
console.log(sorteddates);
//["8/6/2020", "8/18/2020", "1/6/2021", "1/7/2021"]      

2、使用Lodash

let arr = [{
        name: "test1",
        date: "1/7/2021"
    },
    {
        name: "test2",
        date: "1/6/2021"
    },
    {
        name: "test3",
        date: "1/5/2020"
    }
];
arr = _.sortBy(arr, function(dateObj) {
    return new Date(dateObj.date);
});
console.log("sort date", arr);
//[{"name":"test3","date":"1/5/2020"},{"name":"test2","date":"1/6/2021"},{"name":"test1","date":"1/7/2021"}]      

3、使用Lodash(按月和年排序)

let  yearAndMonth  =  [
    { "year": 2016, "month": "FEBRUARY" },
    { "year": 2015, "month": "MARCH" },
    { "year": 2021, "month": "JANUARY" },
    { "year": 2021, "month": "FEBRUARY" }
]
let value= _.sortBy(yearAndMonth, a => new Date(1 + a.month + a.year));
console.log('Sorted Result: ', value);
//[{"year":2015,"month":"MARCH"},{"year":2016,"month":"FEBRUARY"},{"year":2021,"month":"JANUARY"},{"year":2021,"month":"FEBRUARY"}]      

8、從陣列中删除一個項目

1、 pop:此方法從數組中删除最後一個元素并傳回該元素。此方法更改數組的長度。

let arraypoptest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];let testpop = arraypoptest.pop();
console.log("array pop", testpop,"-", arraypoptest);
//10 - [2, 1, 2, 5, 6, 7, 8, 9, 9];      

2、shift:此方法從數組中删除第一個元素并傳回該删除的元素。此方法更改數組的長度。

let arrayshifttest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testshift = arrayshifttest.shift();
console.log("array shift", testshift,"-", arrayshifttest);
//2 - [1, 2, 5, 6, 7, 8, 9, 9, 10]      

3、 slice:此方法将數組的一部分的淺表副本傳回到一個新的數組對象中,該對象選自startto end(end不包括),其中startandend表示該數組中各項的索引。原始數組将不會被修改。

let arrayslicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testslice = arrayslicetest.slice(0, 3);
console.log("array slice", testslice, arrayslicetest); 
//not changed original array
//[2, 1, 2] - [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]      

4、 splice:此方法通過删除或替換現有元素和/或在适當位置添加新元素來更改數組的内容。

let arraysplicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testsplice = arrayslicetest.splice(0, 3);
//[2, 1, 2]      

5、 filter:此方法建立一個新數組,其中所有元素都通過了由提供的功能實作的測試。

數組:

let testarr = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testarr2 = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let filtered = testarr.filter(function(value, index, arr) {
    return value > 5;
});
let filtered2 = testarr2.filter(item => item !== 2);
console.log("filter example 1", filtered);
//[6, 7, 8, 9, 9, 10]
console.log("filter example 2", filtered2);
//[1, 5, 6, 7, 8, 9, 9, 10]      

過濾并去除多個值:

let forDeletion = [2, 3, 5];
let mularr = [1, 2, 3, 4, 5, 3];
mularr = mularr.filter(item => !forDeletion.includes(item));
console.log("multiple value deletion with filter", mularr);
//[1, 4]      

6、delete運算符: JavaScript delete 從對象中删除屬性;如果不再儲存對相同屬性的引用,則最終将自動釋放該引用。

let ar = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
delete ar[4]; // delete element with index 4
console.log(ar);
//[2, 1, 2, 5, undefined, 7, 8, 9, 9, 10]      

7、 lodash删除:_remove删除從所有元素array的是predicate傳回truthy對于和傳回被删除的元素的數組。

let arrlodashtest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let evens = _.remove(arrlodashtest, function(n) {
    return n % 2 == 0;
});
console.log("lodash remove array", arrlodashtest);
//[1, 5, 7, 9, 9]      

9、從對象數組中删除一個項目

1、 pop:此方法從數組中删除最後一個元素并傳回該元素。此方法更改數組的長度。

let users1 = [{
    id: 1,
    name: "ted"
}, {
    id: 2,
    name: "mike"
}, {
    id: 3,
    name: "bob"
}, {
    id: 4,
    name: "sara"
}];
let testpop1 = users1.pop();
console.log(
    "array of objects pop",
    JSON.stringify(testpop1),"-"
    JSON.stringify(users1)
);
//{"id":4,"name":"sara"} - [{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]      

2、shift:此方法從數組中删除第一個元素并傳回該删除的元素。此方法更改數組的長度。

let users2 = [
{ id: 1, name: "ted" },
{ id: 2, name: "mike" },
{ id: 3, name: "bob" },
{ id: 4, name: "sara" }
];
let testshift1 = users2.shift();
console.log("array of objects shift", JSON.stringify(testshift1),"-", JSON.stringify(users2));
//{"id":1,"name":"ted"} - [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]      

3、 slice:此方法将數組的一部分的淺表副本傳回到一個新的數組對象中,該對象選自startto end(不包括end),其中startandend表示該數組中各項的索引。原始數組将不會被修改。

let users3 = [
{ id: 1, name: "ted" },
{ id: 2, name: "mike" },
{ id: 3, name: "bob" },
{ id: 4, name: "sara" }
];
let testslice1 = users3.slice(0, 3);
console.log("array of objects slice", JSON.stringify(testslice1));
//not changed original array
//[{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]      

4、splice:此方法通過删除或替換現有元素和/,或者在适當位置添加新元素來更改數組的内容。

let users4 = [
{ id: 1, name: "ted" },
{ id: 2, name: "mike" },
{ id: 3, name: "bob" },
{ id: 4, name: "sara" }
];
let testspice1 = users3.splice(0, 3);
console.log("array of objects splice", JSON.stringify(testsplice));
//[{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]      

5、filter:此方法建立一個新數組,其中所有元素都通過了由提供的功能實作的測試。

let users7 = [
{ id: 1, name: "ted" },
{ id: 2, name: "mike" },
{ id: 3, name: "bob" },
{ id: 4, name: "sara" }
];
let filterObj = users7.filter(item => item.id !== 2);
console.log("filter example array of objects", filterObj);
//[{"id":1,"name":"ted"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]      

6、lodash删除:_remove删除從所有元素array的是predicate傳回truthy對于和傳回被删除的元素的數組。

let users8 = [
{ id: 1, name: "ted" },
{ id: 2, name: "mike" },
{ id: 3, name: "bob" },
{ id: 4, name: "sara" }
];
let evensObj = _.remove(users8, function(n) {
    return n.id % 2 == 0;
});
console.log("lodash remove array of object", JSON.stringify(evensObj));
//[{"id":2,"name":"mike"},{"id":4,"name":"sara"}]      

10、從數組中給定的字元串中查找字元數

1、字元串比對方法

該match()方法檢索将字元串與正規表達式比對的結果。

const test1 = ("atit patel".match(/a/g)||[]).length
console.log(test1); //2      

2、字元串拆分方法

該split()方法将a String分為子字元串的有序清單,然後将這些子字元串放入數組中,然後傳回該數組。

const test2 ="atit patel".split("a").length-1
console.log(test2); //2      

3、indexOf方法

該indexOf()方法傳回String第一次出現指定值的調用對象内的索引,從開始搜尋fromIndex。如果找不到該值,則傳回-1。

let  stringsearch = "a" ,str = "atit patel";
for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );
console.log(count); //2      

4、filter方法

該filter()方法建立一個新數組,其中所有元素都通過了由提供的功能實作的測試。

const mainStr = 'atit patel';
const test3 = [...mainStr].filter(l => l === 'a').length;
console.log(test3); //2      

5、reduce方法

該reduce()方法在數組的每個元素上執行reducer函數(由你提供),進而産生單個輸出值。

const mainStr1 = 'atit patel';
const test4 = [...mainStr1].reduce((a, c) => c === 'a' ? ++a : a, 0);
console.log(test4); //2      

11、從數組中給定的字元串中查找每個字元的出現次數

1、我們可以添加reduce方法,該方法可以在疊代後傳回對象

let s = 'atit patel';
let test5 = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {});
console.log(test5); //{a: 2,e: 1,i: 1,l: 1,p: 1,t: 3}      

2、與具有“或”運算符的方法6相同

let test6 = [...s].reduce((res, char) => (res[char] = (res[char] || 0) + 1, res), {})
console.log(test6);//{a: 2,e: 1,i: 1,l: 1,p: 1,t: 3}      

12、重命名對象數組中的對象屬性

1、使用Map:此方法建立一個新數組,其中填充了對調用數組中每個元素調用提供的函數的結果。

let countries = [
{ id: 1, name: "india" },
{ id: 2, name: "canada" },
{ id: 3, name: "america" }
];
const transformed = countries.map(({ id, name }) => ({
label: id,
value: name
}));
console.log("1", JSON.stringify(transformed));[{"label":1,"value":"india"},{"label":2,"value":"canada"},{"label":3,"value":"america"}]      

2、使用帶有參數的映射

const transformed2 = countries.map(({ id: label, name: value }) => ({
label,
value
}));
console.log("2", JSON.stringify(transformed2));
[{"label":1,"value":"india"},{"label":2,"value":"canada"},{"label":3,"value":"america"}]      

3、使用lodash:_.mapKeys方法建立一個對象,該對象具有與和相同的值,該對象object和密鑰通過運作objectthru的每個自己的可枚舉字元串鍵控屬性生成iteratee。

const test1= _.mapKeys({ a: 1, b: 2 }, function(value, key) {
return key + value;
});
console.log("3",test1);
//{a1: 1, b2: 2}      

如果我們想重命名對象鍵怎麼辦?讓我們來看看解決方案。

4、将lodash用于值的對象

var users = {
'atit':    { 'user': 'atit',    'age': 40 },
'mahesh': { 'user': 'mahesh', 'age': 15 }
};
const test2 = _.mapValues(users, function(o) { return o.age; });
console.log("4",test2);
//{atit: 40, mahesh: 15}
//shorthand
const test3 =_.mapValues(users, 'age');
console.log("5",test3);
//{atit: 40, mahesh: 15}      

5、使用對象解構:該解構指派文法是JavaScript表達式,使得它可以從陣列解壓縮的值,或從屬性的對象,為不同的變量。

const rename = (({id: a_b_c, ...rest}) => ({a_b_c, ...rest}))
console.log(rename({id: 1, val: 2}))
//{a_b_c: 1, val: 2}      

13、如何合并兩個數組并建立一個新數組?

這可以簡單地通過使用擴充運算符來實作。

var arr1 = ['a', 'b', 'c']
var arr2 = ['d', 'e']
var merged = [...arr1, ...arr2]
console.log(merged)      

14、一個數字數組的總和

1、reduce可用于周遊數組,将目前元素值添加到先前元素值的總和中。

console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)//10      

2、使用Lodash

array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10      

15、比較兩個對象數組,删除重複項,根據屬性合并對象

我們确實需要比較兩個不同的對象數組,并且如果兩個對象比對特定的屬性值,則希望合并這兩個對象,可以使用filter方法來實作。

該filter()方法建立一個新數組,其中所有元素都通過了由提供的功能實作的測試。

讓我們建立測試資料。

let array1 = [
{ id: "50", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 }
];
let array2 = [
{ id: "53", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 },
{ id: "52", active: "a", value: 13 }
];      

讓我們建立函數。

let res = array2.filter(val =>
    array1.some(({
        value
    }) => (val.value as any) === (value as any))
);
console.log("1", JSON.stringify(res));
//[{"id":"53","active":"a","value":10},{"id":"51","active":"a","value":11}]      

16、比較兩個對象數組,合并和更新值(假設數組3,4共享相同的ID)

有時我們确實會獲得要求,以将兩個不同的屬性與新的屬性值合并。我們可以使用地圖建立一組新的對象數組,并且可以使用find方法在更新新值之前比對特定屬性。

該map()方法建立一個新數組,其中填充了在調用數組中每個元素上調用提供的函數的結果。

該find()方法傳回提供的數組中滿足提供的測試功能的第一個元素的值。如果沒有值滿足測試功能,則傳回undefined。(來源:MDN)

讓我們建立測試資料。

let array3 = [
{ id: "50", active: "a", value: 12 },
{ id: "51", active: "a", value: 15 }
];
let array4 = [
{ id: "50", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 },
{ id: "52", active: "a", value: 13 }
];      

讓我們建立函數。

let arr = [];
array3.map(id =>
    arr.push({
        id: id.id,
        newValue: array4.find(o => o.id === id.id).value + 2
    })
);
console.log("2", JSON.stringify(arr));
//[{"id":"50","newValue":12},{"id":"51","newValue":13}]      

17、比較對象數組并找到唯一的對象

如果我們要比較兩個對象數組并檢查其中哪些是唯一對象,則可以使用filter來實作這些功能。

讓我們建立測試資料。

const array5 = [
{ id: "50", active: "a", value: 12 },
{ id: "51", active: "a", value: 15 }
];
const array6 = [
{ id: "50", active: "a", value: 12 },
{ id: "51", active: "a", value: 15 },
{ id: "52", active: "a", value: 13 }
];      

​讓我們建立函數

const ids = array5.map(e => e.id);
let filtered = array6.filter(e => ids.includes(e.id));
console.log("3", JSON.stringify(filtered));
//[{"id":"50","active":"a","value":12},{"id":"51","active":"a","value":15}]      

18、根據比對的值比較和更新屬性

當我們要比較兩個對象數組并根據比對的值更新特定的屬性時,可以使用這些函數。

讓我們建立測試資料

const array7 = [
{ id: "50", active: "a", value: 12 },
{ id: "51", active: "a", value: 15 }
];
const array8 = [{ id: "50", active: "a", value: 12 }];      

讓我們建立函數

const idSet = new Set(array8.map(o => o.id));
const res1 = array7.map(o => ({ ...o, value: idSet.has(o.id) ? "0" : o.value }));
console.log("4", JSON.stringify(res1));
//[{"id":"50","active":"a","value":"0"},{"id":"51","active":"a","value":15}      

19、比較兩個數組對象并獲得差異

當我們要比較兩個不同的對象數組并得到它們之間的差異時,可以使用這些函數。

讓我們建立測試資料

let a = [
{ id: "50", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 }
];
let b = [
{ id: "50", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 },
{ id: "52", active: "a", value: 13 }
];      

讓我們建立函數

let valuesArray1 = a.reduce(function(a, c) {
    a[c.value] = c.value;
    return a;
}, {});
let valuesArray2 = b.reduce(function(a, c) {
    a[c.value] = c.value;
    return a;
}, {});
var result = a
    .filter(function(c) {
        return !valuesArray2[c.value];
    })
    .concat(
        b.filter(function(c) {
            return !valuesArray1[c.value];
        })
    );
console.log("5", result);
//[{"id":"52","active":"a","value":13}]
//shorthand
let ab = b.filter(o => !a.find(o2 => o.id === o2.id));
console.log("6", ab);      

20、比較對象的兩個數組合并并删除重複項

如果我們有要求比較兩個對象數組并從它們中删除重複項并合并兩個數組,則可以使用此方法。

讓我們建立測試資料

let arr1 = [
{ id: "50", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 }
];
let arr2 = [
{ id: "50", active: "a", value: 10 },
{ id: "51", active: "a", value: 11 },
{ id: "52", active: "a", value: 13 }
];      

讓我們建立函數

const arr1IDs = new Set(arr1.map(({ id }) => id));
const combined = [...arr1, ...arr2.filter(({ id }) => !arr1IDs.has(id))];
console.log(JSON.stringify(combined));
//[{"id":"50","active":"a","value":10},{"id":"51","active":"a","value":11},{"id":"52","active":"a","value":13}]      

使用lodash

Lodash支援_differenceBy和 _differenceWith查找兩個數組之間差異的方法。

let lodashtest1 = [{ id: "50" }, { id: "51" }];
let lodashtest2 = [{ id: "50" }, { id: "51" }, { id: "52" }];
let lodashresult = _.differenceBy(lodashtest2, lodashtest1, "id");
console.log("7", JSON.stringify(lodashresult));
//[{"id":"52"}]
let dif = _.differenceWith(lodashtest2, lodashtest1, _.isEqual);
console.log("8",JSON.stringify(dif));
//[{"id":"52"}]      

21、比較對象并找到唯一值

當我們處理嵌套對象時,有時很難弄清楚我們如何疊代和比較兩個嵌套對象并在其中獲得一些唯一的對象。我們可以使用Object.keys和Object.values方法進行疊代。

讓我們建立測試資料

let obj1 = {
val1: "test",
stream: { prop1: false, prop2: true }
};
let obj2 = {
val1: "test",
stream: { prop1: true, prop2: true }
};
interface Data {
stream: { [key: string]: boolean };
}      

讓我們建立測試資料

function objFilter(objA: Data, objB: Data): Data {
let out: Data = { stream: {} };
Object.keys(objA.stream).filter((value, idx) =>
Object.values(objA.stream)[idx] === Object.values(objB.stream)[idx]
? (out.stream[value] = Object.values(objA.stream)[idx])
: false
);
return out;
}
console.log(JSON.stringify(objFilter(obj1, obj2))); //prop2
//{"stream":{"prop2":true}}      

22、如何處理循環内的多個服務調用

1、如果我們不想等待所有服務呼叫完成

let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }];
async function getDetails(values) {
    for (const data of values) {
        const result = await axios.get(
            `serviceURL/${data.id}`
        );
        const newData = result.data;
        this.updateDetails(newData);
        console.log(this.response);
    }
}
function updateDetails(data) {
    this.response.push(data);
}
getDetails(data); //call service to get data      

2、如果我們要等到所有服務呼叫完成

我們可以用promise.all來等到所有的諾言都解決了。

該Promise.all()方法将一個可疊代的Promise作為輸入,并傳回一個Promise解析為輸入Promise結果數組的單個對象。

let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }];
async function getDetails(values) {
    const dataPromises = values.map(entry => {
        return axios.get(
            `serviceURL/${entry.id}`
        );
    });
const resultData = await Promise.all(dataPromises);
resultData.forEach((res: any) => {
        this.updateDetails(res.data);
    });
    console.log(this.response);
}
function updateDetails(data) {
    this.response.push(data);
}
getDetails(data); //call service to get data      

​總結

這22個實用的JavaScript開發小技巧到這裡就全部結束了,希望這些内容對你有所幫助。