Function empty object check - javascript

I need help this task
You have to implement function that will
Check that object is empty.
Object considered to be empty when it has no properties or all its properties are false (I.e. 0, “”, false …)
check object for presence: {},0, “”, symbol(“key”), null, 5,[].

You can use something like this.
This will just loop through the object and check if any value exist and if it does it will just return false else it will return true.
function isEmpty(obj) {
for (let key in obj) {
if(!!obj[key]) return false;
}
return true;
}

You can use 'Object.Values(obj)' which returns an array of all the values from the key value pairs of the object passed as parameter.
'!Object.Values(obj)' will return false if there are no values, which means this is not an object.
'anArray.every(element => { //return a boolean } )' will loop through all the items of the array and return true only if the the arrow function returns true for all 'every' element on the array
function isEmpty (obj){
return !Object.Values(obj) ||
Object.Values(obj).every (v => !v));

Related

How can I check if an object is returned from a filter call?

I'm trying to return true or false, but the filter method returns a new array with the object that matches the return. Is it possible to just return true? I have looked at the includes prototype but that seems to return the entire object as well.
I have tried the following...
let check = this.props.data.filter(obj => {
return obj.idNum.includes(value);
});
let check = this.props.data.map(obj => {
return obj.idNum.includes(value);
});
let check = this.props.data.filter(obj => {
return obj.idNum.includes(value) : true ? false;
});
I'm really just trying to make check true if the array of objects contains the value I'm looking for. I'm checking the idNum for each object for a match.
Take a look at the array .some method. You could use it like so:
let check = this.props.data.some(obj => {
return obj.idNum === value;
});
The some method returns true if the function given to it returns true for any of the array elements.

Why do I get a different output when using an if statement in filter as oppose to just return

I am new to JavaScript and I am learning a little about High Order Functions. I was wondering if someone can tell me why:
function filter_list(arr) {
return arr.filter(function(item) {
return typeof(item) == 'number';
});
}
// input = [1,'a','b',0,15] output = [1,0,15]
But
function filter_list(l) {
return l.filter(function(item){
if (typeof item == "number") {
return item;
}
});
}
// input = [1,'a','b',0,15] output = [1,15]
I am having a hard time seeing the difference.
Filter
Filter returns a value if a condition is true and ignores it if it is false
function filter(arr) {
return arr.filter(function(x) {
return x
})
}
const booleans = [false, false, true]
// this logs only "true"
console.log(filter(booleans))
Truthy and Falsy
Additional to true and false there is truthy and falsy. This means that values evaluat to true or false in condition statements. You can read more on mdn
function getBooleanValue(value) {
return !!value
}
console.log('1 gets cast to:', getBooleanValue(1))
console.log('0 gets cast to:', getBooleanValue(0))
Your Code
The second code snippet didn't returns the 0 because it gets cast to false. To get the expected array you have to change the return value from item to true
function filter_list(l) {
return l.filter(function(item) {
if (typeof item == "number") {
return true;
}
return false
});
}
console.log(filter_list([1, 'a', 'b', 0, 15]))
This is the 'beauty' of javascript. At your first example you return a boolean in your filter. the type of item is equal to number or it isn't
In the second example you return the item itself. So you return 1, 0 and 15. Because 1 is true and 0 is false in programming, javascript sees the returning 0 as a filter failure. So it is filtered. In other words, everything different from 0 is true, and 0 is false.
In the second case:
function filter_list(l) {
return l.filter(function(item){
if (typeof item == "number") {
return item;
}
});
}
item 's value is used to filter or not itself. When item is worth 0, it's equivalent to false therefore, it's not included in the result. The function passed to filter expects a boolean result, if you do not return a boolean, you have to understand how javascript will interprete it.
Check it by yourself, 0 is equivalent false, therefore, if you return 0, the element is going to be filtered:
console.log(false == 0)
Filter checks for Boolean values, it will take 0 and 1 as true and false, so if false == 0, the return 0 wont work.
console.log(filter_list([1,'a','b',0,15]));
function filter_list(l) {
return l.filter(function(item){
if (typeof item == "number") {
return item;
}
});
}
This is because JavaScript has falsy values. Javascript takes null, undefined, 0 & false as falsy.
function filter_list(arr) {
return arr.filter(function(item) {
return typeof(item) == 'number';
});
}
// input = [1,'a','b',0,15] output = [1,0,15]
in this function you return boolean after comparing type, in which case each item that returns true in comparison is selected.
while in this function you are returning values instead of result of comparison, since 0 is falsy value it doesn't get selected for your filtered list.
function filter_list(l) {
return l.filter(function(item){
if (typeof item == "number") {
return item;
}
});
}
// input = [1,'a','b',0,15] output = [1,15]
Filter expects you to provide a boolean variable. This is done in your first example. The second example is just possible because Javascript is not using static types. The item 0 interpreted as boolean is false. So if you do return 0, filter does not append the item.
The two examples you have provided are not at all equivalent.
In the first example you are returning the result of evaluating the expression typeof(item) == 'number' which will either be true or false depending.
In the second you have three fairly different possibilities.
The first two are covered by the if statement: if the type of the item is number you are returning the item itself which may be 'falsey' (zero or NaN) and thus fail the filter or 'truthy' (anything but zero or NaN).
But there's also an implicit return of undefined if the type of item is not number. This doesn't have an impact in a filter because undefined is falsey, but you will likely get unexpected results using copying this pattern to use elsewhere and it should be avoided.
It's because the Array.prototype.filter() creates a new array with all elements for which the test function returns a truthy value (see here: Understanding JavaScript Truthy and Falsy)
And because 0 is falsy it's not part of the returned array in the second sample.

Trying to understand the syntax of this .contain() function

the contain function below is written based on .reduce() function:
_.reduce = function(collection, iterator, accumulator) {
each(collection,function(value){
accumulator=iterator(accumulator,value);
});
return accumulator
};
Im kinda confused by the syntax here, or is it written logically? why we use if statement first and return 'wasFound' first, before set item===target? isn't if item===target is true, we set wasFound to true?
_.contains = function(collection, target) {
return _.reduce(collection, function(wasFound, item) {
if (wasFound) {
return true;
}
return item === target;
}, false);
};
The first time the reduce function makes a match (return item === target) it will subsequently return true for all remaining items to be iterated. There is no reason to check if future values match the target because we only care if the collection contains the target at least 1 time. That is why if wasFound is true it simply returns true.
You use it like this:
_.contains([1,2,3], 2);
//=> true
_.contains([1,2,3], 5);
//=> false
It takes a list and an element. It sets wasFound to false initially and then for each item in the collection checks: (1) if wasFound is true, then some previous item has been identical to target, so set wasFound to true to maintain it, (2) otherwise, set wasFound to the value of item === target.

How to pass a function an object and a property

I want to create the following method:
// expects: (array of objects, name of property on object to compare
to value, value to compare to)
// returns: index of object in array
function findIndex(array, delegate, value) {
for (index in array) {
if (value === array[index].delegate) {
return index;
}
}
};
The above method does not work if I pass in a delegate value that is a string. Is something like this possible?
You can use bracket notation, like so
if (value === array[index][delegate]) {
return index;
}

Iterate thought javascript object to see if it has a certain value

I'm trying to figure out the best way to interate through a javascript object to see if one of the keys is set to a certain value. I understand I can do a foreach loop but I feel like there is an easier way.
var myObject = {
a: false,
b: false,
c: false,
x: false
}
Id like a quick way to return a true if at least one of those values is set to true, and false if all are false.
You have to iterate, but you can do something like this
var hasTrue = Object.keys(myObject).some(function(key) {
return myObject[key];
});
this uses Array.some and stops as soon as a true value is encountered.
FIDDLE
To return the key that has yourValue as its value, just do:
var yourValue = true;
var key = Object.keys(myObject).filter(function (i) {
return myObject[i] === yourValue;
})[0];
It will return undefined if no key found.
If you dont need the key and you only need to know if the value is in your object, you can just use the some method:
var hasValue = Object.keys(myObject).some(function (i) {
return myObject[i] === yourValue;
});
var any_true = false;
JSON.stringify(myObject, function(key, value) {
if (value === true) any_true = true;
});
This uses the callback feature of JSON.stringify. It has the advantage that it finds any true value, even in nested objects.

Categories