複雑な配列グループ化JavaScript
このようなオブジェクトの配列があるとします-
const arr = [ {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6}, {userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15}, {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181}, {userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190} ];
そのような配列を1つ取り込むJavaScript関数を作成する必要があります。関数は、「from」プロパティと「to」プロパティに基づいて重複するオブジェクトを次のような単一のオブジェクトにグループ化する必要があります-
const output = [ {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 15}, {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 190} ];
例
const arr = [ {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6}, {userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15}, {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181}, {userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190} ]; const groupByDuration = (arr = []) => { const result = arr.reduce((acc, val) => { let last = acc[acc.length - 1] || {}; if (last.userId === val.userId && last.to + 1 === val.from) { last.to = val.to; } else { acc.push({ userId: val.userId, from: val.from, to: val.to }); } return acc; }, []); return result; } console.log(groupByDuration(arr));
出力
そして、コンソールの出力は-
になります[ { userId: '3t5bsFB4PJmA3oTnm', from: 1, to: 15 }, { userId: '3t5bsFB4PJmA3oTnm', from: 172, to: 190 } ]
-
JavaScriptの配列reverse()
JavaScript配列reverse()関数は、配列内の要素の順序を逆にします 以下は、配列のreverse()関数のコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document&
-
JavaScriptでの配列の分解。
破棄すると、配列から値が解凍されます。以下は、JavaScriptでの配列の非構造化のコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <