2017-07-27 13 views
-2

配列がA = [1, 4, 3, 2]およびB = [0, 2, 1, 2]の場合、値[0, 2, 2, 0]の新しい配列(A - B)を返したいとします。これをjavascriptで行う最も効率的なアプローチは何ですか?マップ・メソッドは、その中に3つのパラメータを取ります javascript内の別の配列から1つの配列を減算する方法

+4

の可能性のある重複した[JavaScript配列を使用して設定差を計算する最速または最もエレガントな方法は何ですか?](https://stackoverflow.com/questions/1723168/what-is – jhpratt

+0

あなたの担当者と一緒にいるユーザーは、問題の共有作業の重要性を知っている必要があります。あなたの問題の解決策ではなく、あなたの問題に対する解決策を得ることです。 – Rajesh

+0

お試しください。 https://stackoverflow.com/questions/1187518/javascript-array-difference – ImAnand

答えて

7

使用map方法は

var a = [1, 4, 3, 2], 
 
    b = [0, 2, 1, 2] 
 

 
var x = a.map(function(item, index) { 
 
    // In this case item correspond to currentValue of array a, 
 
    // using index to get value from array b 
 
    return item - b[index]; 
 
}) 
 
console.log(x);

currentValue, index, array 

以下

0

For今までシンプルかつ効率的のようなコールバック関数です。ここ

チェック:JsPref - For Vs Map Vs forEach

var a = [1, 4, 3, 2], 
 
    b = [0, 2, 1, 2], 
 
    x = []; 
 

 
for(var i = 0;i<=b.length-1;i++) 
 
    x.push(a[i] - b[i]); 
 
    
 
console.log(x);

+0

両方の配列の長さは同じであるとします。それ以外の場合、問題が発生する可能性があります。または前にそれを処理します。 –

+0

@AvneshShakyaはい。どちらの配列も同じでなければならず、それは尋ねられたものです。 – Sankar

0

あなたは単に配列forEachためのforEachメソッドを使用することができます最初のテーブルの値を上書きしたい場合。 ForEachメソッドは、mapメソッド(element、index、array)と同じパラメーターをとります。 mapキーワードを使った前回の回答と似ていますが、ここでは値を返すのではなく、独自の値を割り当てています。

var a = [1, 4, 3, 2], 
 
    b = [0, 2, 1, 2] 
 
    
 
a.forEach(function(item, index, arr) { 
 
    // item - current value in the loop 
 
    // index - index for this value in the array 
 
    // arr - reference to analyzed array 
 
    arr[index] = item - b[index]; 
 
}) 
 

 
//in this case we override values in first array 
 
console.log(a);

関連する問題