The goal of this exercise is to take an array of items: objects, arrays, numbers, strings and null, and return only true objects. Both null and arrays are objects in Javascript, so I have to test for those specifically. First I used the reduce method. On line 7, I test if an item is null or an array and exclude it from the accumulator. Then on line 11, I test to see if it is an object (that is not null or an array) and add it to the accumulator. On line 17 I skip all other types (number and string) by returning the accumulator without adding the item.
// Shorten array to consist only of the two objects
const arr=[{one: 'two'}, 3, 'four', {five: 'six'}, null, undefined, 7, ['eight']];
function returnObj(a,b) {
//check if item is null or array and ignore
if (b===null || Array.isArray(b)) {
return a;
// if b is an object that is not null or array,
// add to accumulator
} else if (typeof(b) === 'object') {
a.push(b);
console.log('a.push', a);
return a;
} else {
// otherwise ignore it (string and number)
return a;
}
}
const output=arr.reduce(returnObj,[]);
console.log("OUTPUT:",output);
// OUTPUT: [ { one: 'two' }, { five: 'six' } ]
Next, I doing it using the filter() method, which makes the code much more streamlined. I do all the testing on line 5 to make sure the item is an object, but is not null and not an array.
// OPTION 2 - FILTER METHOD
const arr=[{one: 'two'}, 3, 'four', {five: 'six'}, null, undefined, 7, ['eight']];
function returnObj(item) {
return item !==null && !Array.isArray(item) && typeof(item) === 'object';
}
const output = arr.filter(returnObj);
console.log("OUTPUT:", output);
// OUTPUT: [ { one: 'two' }, { five: 'six' } ]