Aessandro
Aessandro

Reputation: 5761

JS filter method returns an empty array when assigned to a variable

I have the following code:

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);

which returns an empty array

if I remove "console.log(data1)" and I modify the code as follow:

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

I get the desired result.

Why is data1 empty?

Upvotes: 2

Views: 633

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can't use filter() method, instead you can use reduce() and forEach() and return array as result.

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);

Upvotes: 4

Related Questions