Every function with Object.values not working - javascript

I have an object and I need to check if all the values are true.
{
condition1: true,
condition2: true,
condition3: false
}
Ive used Object.value to get an array of the true and false values. However I cant seem to get the every function to work, it always returns true.
const test = Object.values(equipmentSelection)
.every((element) => {
if (element = true) return true;
});

Just return the element without using conditional check, you can do like this
const test = Object.values(equipmentSelection)
.every(element => element)
});

You are using an assignment operator = instead of a logical == or === operator. So you are basically setting element to be equal to true and then use this same value (true) as the condition of if. So the if condition is always true and thus true is returned for each element in the array.
Since element is of type boolean, you don't need the if statement, just use its value:
.every(element => element);

You can do this.
const test = Object.values(equipmentSelection)
.every(element => element===true);
And like others have said,
.every( element => element);
Will return the elements value which is with true or false and that’s what you will get with the comparisons.

Related

Javascript search an array for a value starting with a certain value

I am looking for a way to search an array to see if a value is present that starts with the search term.
const array1 = ['abc','xyz'];
So a search for 'abcd' would return true on the above.
I have been playing about with includes, but that only seems to check the full value.
Also, startsWith I dont think will work as I believe that checks a string and not values in an array??
You can use the find() function which allows you to pass a custom function in parameter that will be tested on each value. This way you can use startsWith() on each value of the array as you intended to do.
Example:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
});
}
console.log(findStartWith("hello")); // undefined
console.log(findStartWith("abcd")); // abc
console.log(findStartWith("xyzz")); // xyz
If you want to return true or false instead of the value, you can check if the returned value is different from undefined.
function findStartWith(arg) {
return !!array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
The same snippet with a boolean:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
console.log(findStartWith("hello")); // false
console.log(findStartWith("abcd")); // true
console.log(findStartWith("xyzz")); // true

Where to use additional condition when using Array methods

I was trying to solve the following question:
Write a function that returns true if all array elements are true. Use reduce
The is the solution I made up
function allTrue(values) {
if ( values[0] === false) return false
if (values.length === 0) return true
let result = values.reduce( (final, value) => final = value === true, true)
return result ? true : false
}
My question is, whether it is possible to move the external conditions into the reduce method's body or not.
In other words, if I was required to use a single reduce method to solve it, can I implement it?
I tried manipulating the final in the reduce, but it is modified later in next iterations
For instance the following test should return false but returns true
allTrue([false, true])
Any explanation would be appreciated, thank you
The reason your code doesn't work is that the reduce only returns the result of the comparison of the last element in the array with true. Since the last element in [false, true] is true, it returns true.
Note that your code is overly complex, you have already effectively included your conditions in the reduce (giving an initial value of true means that a zero-length array will return true). Your one issue is that the code in the reduce is incorrect, you should be checking whether all the previous values are true as well as the current one by and'ing the current value with the and of all the previous values:
const allTrue = (values) => values.reduce((curr, value) => curr && value, true);
console.log(allTrue([]));
console.log(allTrue([true]));
console.log(allTrue([false]));
console.log(allTrue([true, true, true]));
console.log(allTrue([false, true]));
I think this can be help:
function allTrue(values) {
return values.reduce((final, value) => final && value)
}
We can use every as well to find the solution to this. Below is the snippet for both every as well as reduce
var allTrue_Every = (arr) => arr.every(d => d == true)
console.log(allTrue_Every([true, true]))
console.log(allTrue_Every([true, false]))
var allTrue_Reduce = (arr) => arr.reduce((r, d) => r && d, true)
console.log(allTrue_Reduce([true, true]))
console.log(allTrue_Reduce([true, false]))

Best way to get a decent result from this Array check?

I am trying to get a decent result that I can do something with, but feel the way I am it at the moment in the 'check' function isn't actually returning other than an expression:
validate = () => {
const items = this.state.data;
const check = e => {
!e.error === undefined ? true : false;
};
const checkFields = items.some(check);
if (!checkFields) {
alert('form valid');
}
};
Is the 'check' function any good?
The check function does not return anything. Either:
Remove the braces so that it no longer is a code block, but an expression whose value is returned, or
Add a return before the expression.
Secondly:
The ! operator has precedence over ===, so !e.error === undefined is not doing what you think. You can use parentheses, like !(e.error === undefined), but why not just e.error !== undefined?
And it really is not necessary to apply the ternary operator on that. It is already a boolean expression, so just use it without that ? true : false.
In short:
const check = e => e.error !== undefined;
Concerning the overall function validate: Using alert is quite primitive, and not the most user-friendly thing to do. You should consider applying CSS styling to the input that does not pass validation.

Storing and getting boolean with Redis

I'm trying to use Redis to store and get a boolean for my toggle function.
The dependecy what I'm using is redis-js I can set the value false with key to redis but getting the valu from redis is always false.
Say first store the key value to Redis
redis.set('myKey', 'false');
Get the value
let toggle = redis.get('myKey');
toggle = !toggle;
Store
redis.set('myKey', toggle);
Get
const checkStatus = redis.get('myKey');
return checkStatus;
I'm expecting the output will be true -> false if executed the function two times.
For your toogle to work you've to explicitly check if the value you get is equal to the string 'false'.
let toggle = redis.get('myKey');
toggle = toogle === 'false'
Converting the string 'false' to boolean results to true not false and negating it you get false.
From MDN
All other values, including any object or the string "false", create an object with an initial value of true
Here's an illustration:
const val = 'false'
const toggle = !val; // this is equivalent to !Boolean(val)
const bool = Boolean(val) // get boolean
const negated = !bool // negate
console.log('toggle: ', toggle);
console.log('bool: ', bool); // Boolean("false") gives true
console.log('negated: ', negated);
You run command redis.get, the return value type is String not Boolean.
So you should't use ! operator, you can compare with 'true' or 'false', then assign a value

Am I using filter right? I don't know why this solution works

I'm going through FCC basic algorithms right now, and while I passed the exercise, I'm not fully understanding why it works, as when I change things to how I think they should be it doesn't work, but when I change things so they look wrong to me it still works.
For instance, I change true to false, and it still works, or I just type true, and it still works, or I just say return value, and it works. Does filter automatically remove falsy values?
Here is my code. My original code that didn't work said if (value === true).
function bouncer(arr) {
let x = arr.filter(value => {
if (value !== true)
return value;
})
console.log(x);
return x;
}
bouncer([7, "ate", "", false, 9]);
Remove all falsy values from an array.
Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.
UPDATE
Thanks for all the answers, they were all super helpful in clearing up my confusion.
function bouncer(arr) {
let x = arr.filter(ages => {
return ages;
})
return(x);
}
bouncer([7, "ate", "", false, 9]);
This is the solution I ended up re-writing, and now understand why I did what I did.
Your callback,
if (value !== true)
return value;
is equivalent to just
return value;
in your case because none of the elements in your array are true, so value !== true always holds.
If you change it to
if (value !== false)
return value;
it still executes return value; for most array elements. The only exception is false, for which your function returns undefined (because no explicit return statement is executed). undefined is falsy, so it is treated the same as return false by filter (because filter only cares whether the callback returned a true or falsy value). So in the end not returning a value if the element is false is the same as return value.
On the other hand, if you change it to
if (value === true)
return value;
then your callback would return true if the current element is true and return undefined for any other value. The net effect is removing all elements that are not true (which in your case is all elements because your input array does not contain true).
If you want to remove falsy values, you can simply say
arr.filter(value => { return value; })
// or:
arr.filter(value => value)
because you're using the value itself as the condition: Anything that looks falsy is removed by filter; anything that looks true is kept.
If you find this confusing, perhaps looking at this custom (and simplified) filter implementation clears things up:
function my_filter(arr, fn) {
var results = [];
for (var i = 0; i < arr.length; i++) {
if (fn(arr[i])) {
results.push(arr[i]);
}
}
return results;
}
// Usage would be something like:
console.log(my_filter([7, "ate", "", false, 9], value => value));
If your purpose is to return an array that only retains the truthy values, then do this:
.filter(Boolean)
In your callback to filter you don't always return a value, and if you don't, that means the corresponding value will not be retained. Furthermore, with operators like !== and === you are doing a strict comparison. So value === true will only match true, not any other truthy value. Similarly, value !== true will still match some truthy values (that are not true).
filter iterates over your array. In each element iteration the callback is called.
If you return a "truthy" value in the callback that element is kept in the resulting Array, otherwise it's not.
Your confusion stems from the fact that you think you need to return the value argument in some way. You don't.
Look at this example:
var animals = ['dog', 'dog', 'cat', 'cat']
var cats = animals.filter(value => {
if (value === 'cat') {
return true
} else {
return false
}
})
console.log(cats)
Of course the above can be simplified to this:
var animals = ['dog', 'dog', 'cat', 'cat']
var cats = animals.filter(value => {
return value === 'cat'
})
console.log(cats)
That's just it.

Categories

Resources