2016-10-25 5 views
2

に割り当てられた空の配列を返しI持って次のコードを私は削除する場合は、空の配列JSフィルタ方法は、変数

を返し

var test1 = [ 
    { 
    id: 1 
    }, 
    { 
    id: 2 
    }, 
    { 
    id: 3 
    }, 
]; 

var test2 = [ 
    { 
    id: 3, 
    text: 'some other text 3' 
    }, 
    { 
    id: 2, 
    text: 'some other text 2' 
    } 
]; 

// filter method 
function getNewArray(val) { 
    test2.filter(function(val2){ 
    if(val.id == val2.id){ 
     return (val2.text); 
     } 
    }); 
} 
var data1 = test1.filter(getNewArray); 

console.log(data1); 

「はconsole.log(DATA1)を」とI次のようにコードを変更してください:

function getNewArray(val) { 
    test2.filter(function(val2){ 
    if(val.id == val2.id){ 
     console.log(val2.text); 
     } 
    }); 
} 

私は望ましい結果を得ます。

なぜdata1が空ですか?

+0

機能します。私はあなたの問題を解決するかどうかは分かりませんが、あなたが望むのは 'test2.filter(function(val2){return val.id == val2.id;})'(またはラムダ 'test2.filter (val2 => val.id == val2.id) ') – Aaron

+0

あなたが欲しいものは不明です(私にとって)。希望の結果を追加してください。 –

+1

フィルタは新しい配列を返すため、現在の配列は変更されません。あなたはあなたの機能から何も返さない。 – epascarello

答えて

4

filter()メソッドを使用することはできません。reduce()forEach()を使用し、結果として配列を返すことができます。それが保持又は除外されるべきである場合、配列の各要素について表すブール値を返す必要がありArray.prototype.filter` `に渡さ

var test1 = [{ 
 
    id: 1, 
 
    text: 'some text' 
 
}, { 
 
    id: 2, 
 
    text: 'some text 2' 
 
}, { 
 
    id: 3, 
 
    text: 'some text 3' 
 
}, ]; 
 

 
var test2 = [{ 
 
    id: 3, 
 
    text: 'some other text 3' 
 
}, { 
 
    id: 2, 
 
    text: 'some other text 2' 
 
}]; 
 

 
function getNewArray(r, val) { 
 
    test2.forEach(function(val2) { 
 
    if (val.id == val2.id) { 
 
     r.push(val2.text); 
 
    } 
 
    }); 
 
    return r; 
 
} 
 
var data1 = test1.reduce(getNewArray, []); 
 

 
console.log(data1);

関連する問題