Reputation: 57
Below is the array of objects. what we have to do is to
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" }
];
what I have tried is
var obj1 = {};
var prop1 = [];
var prop2 = [];
arr.forEach(el=>{
if(el.id!==0 || el.id!==null || el.id!==undefined || el.id!==NaN){
prop1.push(el)
}
else{
prop2.push(el)
}
})
console.log(prop1)
console.log(prop2)
but it is not working
output I receive -
1] [{id: 15}, {id: -1}, {id: 0}, {id: 3}, {id: 12.2}, {}, {id: null}, {id: null}, {id: "undefined"}]
2] []
expected -
1] [{id: 0}, {id: null}, {id: "undefined"}]
2] [{id: 15}, {id: -1}, {id: 3}, {id: 12.2}]
Upvotes: 0
Views: 898
Reputation: 49945
You can cast to boolean (!el.id
) which will handle most cases and you have to deal with "undefined"
separately:
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" }
];
var obj1 = {};
var prop1 = [];
var prop2 = [];
arr.forEach(el=>{
if(!el.id || el.id === "undefined"){
prop1.push(el)
}
else{
prop2.push(el)
}
})
console.log(prop1);
console.log(prop2);
console.log(prop1.length);
console.log(prop2.length);
Upvotes: 2
Reputation: 584
Try this:
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" }
];
let filterArray = arr.filter((el) => {return !el.id || [0,null,"undefined",NaN].includes(el.id)});
console.log(filterArray);
let filterArray1 = arr.filter((el) => {return el.id && ![0,null,"undefined",NaN].includes(el.id)});
console.log(filterArray1);
Upvotes: 1
Reputation: 80
why does it not work? Is the ordering incorrect or is there a JavaScript error?
The code looks fine at the first glance, you may use if (!el.id), which checks if the id is "falsy" (0, null, undefined, NaN, false)
You may also have a look at the methods "map" and "filter", https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Upvotes: 0