22个实用JavaScript编程知识,可帮助你提升面试成功率

web前端开发

共 20917字,需浏览 42分钟

 ·

2021-05-06 17:49


英文 | 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://stackblitz.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); // truelet 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);//truelet 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 Descendinglet 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 4console.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)||[]).lengthconsole.log(test1); //2

2、字符串拆分方法

该split()方法将a String分为子字符串的有序列表,然后将这些子字符串放入数组中,然后返回该数组。

const test2 ="atit patel".split("a").length-1console.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}//shorthandconst 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}]//shorthandlet 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开发小技巧到这里就全部结束了,希望这些内容对你有所帮助。
感谢你的阅读,有什么问题也可以评论区里留言交流。


学习更多技能

请点击下方公众号



浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报