ホームページ >ウェブフロントエンド >jsチュートリアル >JavaScript で一意の項目に基づいて配列を結合するにはどうすればよいですか?
JavaScript での一意の項目による配列の結合
JavaScript では、オブジェクトのプロパティとループの組み合わせを使用して、一意の項目に基づいて配列を結合できます。関数.
解決策:
まず、結合された結果を格納する空の配列 newCells を作成します。次に、元の配列の各要素を反復処理します。
<code class="js">for (var i = 0; i < totalCells.length; i++) { var lineNumber = totalCells[i].lineNumber; // Check if an object for the current line number already exists in newCells if (!newCells[lineNumber]) { // Create a new object with the line number and an empty array to store cell widths newCells[lineNumber] = { lineNumber: lineNumber, cellWidth: [] }; } // Add the current cellWidth to the array in the new object newCells[lineNumber].cellWidth.push(totalCells[i].cellWidth); }</code>
このコードは、totalCells 配列を反復処理して、現在の行番号を持つオブジェクトが newCells にすでに存在するかどうかを確認します。そうでない場合は、行番号を含む新しいオブジェクトを作成し、空の cellWidth 配列を初期化します。次に、現在のセル幅を cellWidth 配列にプッシュします。
結果の newCells 配列には、一意の lineNumber プロパティを持つオブジェクトと、行番号に基づいて結合された cellWidth 値の配列が含まれます。
出力例:
上記のソリューションを提供されたサンプル入力に適用すると:
<code class="js">totalCells = [ { cellwidth: 15.552999999999999, lineNumber: 1 }, { cellwidth: 14, lineNumber: 2 }, { cellwidth: 14.552999999999999, lineNumber: 2 }, { cellwidth: 14, lineNumber: 1 } ]; // Code to combine arrays based on unique line numbers // ... // Output console.log(newCells);</code>
出力は次のようになります:
<code class="js">[ { lineNumber: 1, cellWidth: [15.552999999999999, 14], }, { lineNumber: 2, cellWidth: [14, 14.552999999999999], }, ]</code>
以上がJavaScript で一意の項目に基づいて配列を結合するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。