소스 검색

数组处理

kindring 3 년 전
부모
커밋
be692ed14a
1개의 변경된 파일20개의 추가작업 그리고 1개의 파일을 삭제
  1. 20 1
      test/test.js

+ 20 - 1
test/test.js

@@ -1,3 +1,11 @@
+/*
+ * @Author: your name
+ * @Date: 2021-08-13 17:17:06
+ * @LastEditTime: 2021-08-20 17:08:58
+ * @LastEditors: Please set LastEditors
+ * @Description: In User Settings Edit
+ * @FilePath: \md-\test\test.js
+ */
 // 雷姆提问,如何将两个数组中key值同样的项合并
 const arr = [
     {key: 1, a: 'a'},
@@ -38,4 +46,15 @@ const res = [...map.values()]
 console.log(res)
 
 // 晨晨的一行版本
-arr.reduce((r, o) => ((r[o.key] = {...r[o.key], ...o}), r), []).filter(i => i)
+let x = arr.reduce((r, o) => ((r[o.key] = {...r[o.key], ...o}), r), []).filter(i => i)
+console.log(x)
+
+// 晨晨大佬一行版本修改
+let x2 = arr.reduce((r,o)=>{
+    // 通过解构进行合并不同的项
+    r[o.key] = {...r[o.key], ...o}
+    return r
+},[])
+// 因为key值不是百分百都对应数组的下标.所以用filter过滤
+x2 = x2.filter(i=>i)
+console.log(x2);