Home > Mobile >  Array filtering in JavaScript is returning an empty array
Array filtering in JavaScript is returning an empty array

Time:09-22

// console.log("Testing Merging of data");

const Array_1 = [{ class_1: 4, HeadTeacher: "Mrs Joe" }];
const Array_2 = [{ class_1: 10, HeadTeacher: "Loveth" }];
const Array_3 = [{ class_1: 1, HeadTeacher: "Itunu" }];
const Array_4 = [{ class_1: 1, HeadTeacher: "John" }];

const result = [...Array_1, ...Array_2, ...Array_3];

const Final = result.filter((item, index) => {
  return item.class_1 === 10 && item.class_1 === 1;
});

console.log(Final);

//  Expected result
// [{ class_1: 1, HeadTeacher: "Itunu" }, { class_1: 1, HeadTeacher: "John" }; ];

// Out put ; Empty array []

I have an array of objects which I'm filtering to return certain results based on my filter criteria. but all I did was just returning an empty array.

CodePudding user response:

The reason why your array output is different from your expected result is your condition when returning.

  • You are using logical AND (&&). You should change && to ||.

CodePudding user response:

Use OR(||) operation instead of AND(&&).

Correct Code ->

const Array_1 = [{ class_1: 4, HeadTeacher: "Mrs Joe" }];
const Array_2 = [{ class_1: 10, HeadTeacher: "Loveth" }];
const Array_3 = [{ class_1: 1, HeadTeacher: "Itunu" }];
const Array_4 = [{ class_1: 1, HeadTeacher: "John" }];

const result = [...Array_1, ...Array_2, ...Array_3];

const Final = result.filter((item, index) => {
  return item.class_1 === 10 || item.class_1 === 1;
});

console.log(Final);
  • Related