
JavaScript编程知识
发布日期:2021-05-10 03:43:35
浏览次数:18
分类:精选文章
本文共 12306 字,大约阅读时间需要 41 分钟。
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"]}
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"]}
3、使用 Set
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 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"]}
3、在数组中查找一个项目
以下是查找数组中项目的多种方法。
1、includes
console.log(array.includes(2)); // 输出 true
2、every
let testevery1 = array.every(val => val > 3); // false
3、some
let testsome1 = array.some(val => val > 3); // true
4、lodash includes
let lodashtest9 = _.includes(array, 1); // truelet lodashtest10 = _.includes(array, 3, 2); // false
5、findIndex
let testindex = array.findIndex(val => val > 1); // 0
6、find
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]
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
let lodashtest11 = _.includes({ 'a': 1, 'b': 2 }, 1); // truelet lodashtest12 = _.includes('abcd', 'bc'); // true
4、findIndex
let testindex2 = users.findIndex(val => val.id > 1); // 3
5、find
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、对数组项排序
const months = ['March', 'Jan', 'Feb', 'Dec'];months.sort(); // 输出 ['Dec', 'Feb', 'Jan', 'March']const array1 = [1, 30, 4, 21, 100000];array1.sort(); // 输出 [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)));
2、localeCompare
let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id)));
3、多字段排序
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;});
4、Lodash _sortBy
let sorttest6 = _.sortBy(data, ["id", "city"]);
7、对日期数组进行排序
1、使用 sort
let isDescending = false; // 设置为 true 逆序排序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());
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);});
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));
8、从阵列中删除一个项目
1、pop
let arraypoptest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];let testpop = arraypoptest.pop(); // 输出 10
2、shift
let arrayshifttest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];let testshift = arrayshifttest.shift(); // 输出 2
3、slice
let arrayslicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];let testslice = arrayslicetest.slice(0, 3); // [2, 1, 2]
4、splice
let arraysplicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];let testsplice = arrayslicetest.splice(0, 3); // [2, 1, 2]
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(); // 输出 {"id":4,"name":"sara"}
2、shift
let users2 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" }];let testshift1 = users2.shift(); // 输出 {"id":1,"name":"ted"}
3、slice
let users3 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" }];let testslice1 = users3.slice(0, 3); // [{"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); // [ {"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"} ]
10、从数组中给定的字符串中查找字符数
1、match
const test1 = ("atit patel".match(/a/g) || []).length; // 2
2、split
const test2 = "atit patel".split("a").length - 1; // 2
3、indexOf
let stringsearch = "a";let str = "atit patel";let count = -1;let index = -2;while (index !== -1) { index = str.indexOf(stringsearch, index + 1); if (index === -1) break; count++;}console.log(count); // 2
4、filter
const mainStr = 'atit patel';const test3 = [...mainStr].filter(l => l === 'a').length; // 2
5、reduce
const mainStr1 = 'atit patel';const test4 = [...mainStr1].reduce((a, c) => c === 'a' ? ++a : a, 0); // 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、简化 reduce
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(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(JSON.stringify(transformed2)); // [{"label":1,"value":"india"},{"label":2,"value":"canada"},{"label":3,"value":"america"}]
3、使用 lodash mapKeys
const test1 = _.mapKeys({ a: 1, b: 2 }, function(value, key) { return key + value;});console.log(test1); // {a1: 1, b2: 2}
4、使用 lodash mapValues
var users = { 'atit': { user: 'atit', age: 40 }, 'mahesh': { user: 'mahesh', age: 15 }};const test2 = _.mapValues(users, o => o.age); // {atit: 40, mahesh: 15}const test3 = _.mapValues(users, 'age'); // {atit: 40, mahesh: 15}
5、使用对象解构
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); // ['a', 'b', 'c', 'd', 'e']
14、一个数字数组的总和
1、使用 reduce
console.log([1, 2, 3, 4].reduce((a, b) => a + b, 0)); // 10console.log([].reduce((a, b) => a + b, 0)); // 0
2、使用 Lodash
let array = [1, 2, 3, 4];let sum = _.sum(array); // sum == 10
15、比较两个对象数组,删除重复项,根据属性合并对象
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 === value));console.log(JSON.stringify(res)); // [{"id":"53","active":"a","value":10},{"id":"51","active":"a","value":11}]
16、比较两个对象数组,合并和更新值(假设数组3,4共享相同的ID)
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 => { const obj = array4.find(o => o.id === id.id).value + 2; arr.push({ id: id.id, newValue: obj });});console.log(JSON.stringify(arr)); // [{"id":"50","newValue":12},{"id":"51","newValue":13}]
17、比较对象数组并找到唯一的对象
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(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(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((a, c) => a[c.value] = c.value, {});let valuesArray2 = b.reduce((a, c) => a[c.value] = c.value, {});let result = a .filter(c => !valuesArray2[c.value]) .concat(b.filter(c => !valuesArray1[c.value]));console.log(JSON.stringify(result)); // [{"id":"52","active":"a","value":13}]
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}// ]
21、比较对象并找到唯一值
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) => { const currentA = Object.values(objA.stream)[idx]; const currentB = Object.values(objB.stream)[idx]; if (currentA === currentB) { out.stream[value] = currentA; } }); return out;}console.log(JSON.stringify(objFilter(obj1, obj2))); // {"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}`); this.updateDetails(result.data); console.log(this.response); }}getDetails(data); // 发送服务调用
2、等待所有服务调用
let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }];async function getDetails(values) { const dataPromises = values.map(entry => axios.get(`serviceURL/${entry.id}`)); const resultData = await Promise.all(dataPromises); resultData.forEach(res => { this.updateDetails(res.data); }); console.log(this.response);}getDetails(data); // 发送服务调用
发表评论
最新留言
表示我来过!
[***.240.166.169]2025年05月03日 13时41分25秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
moment时间处理相关小结
2025-04-14
mongo - 正常关闭服务
2025-04-14
mongo db 使用方法
2025-04-14
mongo 去重
2025-04-14
MongoDB
2025-04-14
MongoDB - 库、集合、文档(操作 + 演示 + 注意事项)
2025-04-14
MongoDB - 整合 SpringBoot 操作全流程
2025-04-14
MongoDB - 索引底层原理和使用,聚合的使用(案例 + 演示)
2025-04-14
MongoDB 3.0 增删改查及聚合操作,pymongo
2025-04-14
mongoDB 3.0 安全权限访问控制
2025-04-14
mongodb linux安装
2025-04-14
MongoDB MapReduce使用
2025-04-14
MongoDB Replica Sets + Sharding 实战
2025-04-14
Mongodb sharding转换一个副本集为分片集群
2025-04-14
mongodb 与 c++ 的配合使用
2025-04-14
MongoDB 分片集群技术
2025-04-14
MongoDB 启动基于角色的登录认证功能
2025-04-14