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.
Related
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));
(except foreach,map,reduce,filter, for, while and do while)
(return true(if no object with attribute read : false found) or false(if any one of the objects contains property read : false).)
Consider the following array:
let allRead = true;
let notifications = [
{message: ‘Lorem’, read: true},
{message: ‘Ipsum’, read: true},
{message: ‘Dolor’, read: true},
{message: ‘Sit’, read: false},
{message: ‘Amet’, read: true}
];
You have to set the allRead variable to false using a built-in higher-order function on the
notifications array. Conditions: a) You cannot use for, while, do-while loops b) You cannot use
forEach(), map(), reduce(), filter().
So far I have used some and find. I am pretty sure its not find because find always returns the whole object. you cannot return other thing than what you iterate.
allRead = notifications.find((obj) => {
console.log("yes");
if (obj.read === false) {
console.log(obj.read);
return obj;
}
});
console.log(allRead);
on the other hand , using some has been a partial success...but it returns true when read : false found but what i want is that if read: false found then set the allRead to false, regardless of other iterations.
allRead = notifications.some((not) => not.read !== true);
console.log(allRead);
I have also noticed that if I use a if else condition or switch case statement and return true, false based on condition...then when it returns true it autometically breaks and avoids the other iteraions.
allRead = notifications.some((not) => {
switch (not.read) {
case false:
break;
return false;
default:
return true;
}
});
console.log(allRead);
You can use Array#every to check if all elements in an array match a given condition.
const allRead = notifications.every(({read})=>read);
You can also use Array#some by simply negating the result to check if there was no element that matched the condition.
const allRead = !notifications.some(({read})=>!read);
If you want to check all values in a array list (in this case array of objects) needs to pass certain condition to return true if not false, array.every can be used.
Need more info or example, if this not what you are looking for..
Ref MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
I am trying to solve an extra credit problem using recursion. Basically there is a "tree" that has matching "leaves" and I need to use recursion to check those matching leaves and return true if they match and return false if they do not.
I have no idea how to do this and no materials I can find are helping me understand recursion any better. This is for an online program to learn how to program.
Any help would be appreciated!
Psuedo:
// initialize some value
// initialize some flag.. boolean
// initialize some helper function and pass obj...leaf checker recursive function
// check all the keys ...for loop/forEach
// if a key is an object && value is undefined
// assign value
// return
// if a value is an object ==> recurse
// if a value is found and it doesn't match our initial value
// trip our flag to false
// return
// return true or false
const checkMatchingLeaves = (obj) => {
};
My attempt:
const checkMatchingLeaves = (obj) => {
// return true if every property on `obj` is the same
// otherwise return false
let checker = Object.values(obj);
if (Object.values(obj).length === 1) return true;
if (checker.map(checker[i] === checker[i + 1])) {
i > checker.length; i++;
}
};
This isn't exactly what (I think) you're asking for, but you should be able to use it as a template to figure out what to do:
// searchTree takes a value to try to match and an array/primitive
// value.
function searchTree(val, node) {
// Check if it's a value or an array. If it's a value we can
// do the test and return, otherwise we recursively call
// searchTree on all the children.
// Array.some returns true if any of the function calls return
// true. This is a shorthand for your boolean flag: it lets us
// return early as soon as we find a match.
return Array.isArray(node) ?
node.some(child => searchTree(val, child)) : // recursive call
val === node;
}
searchTree(3, [1, 2, [8], [[[3]]]]); // true
searchTree('abc', 'a'); // false
searchTree('abc', ['ab', 'bc', ['abc']]); // true
This is a DFS search implementation.
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.
im a JS newbie. Trying to figure out this problem below. I am stuck on the "if" statement and not sure exactly what to put in. Also im not sure if my "push" is setup right
// Define a function named `compact` that accepts an array and returns
// another array with all the falsey values removed from it. For example,
// if this array was passed in:
// [1, 4, 0, '', undefined, false, true, null, {mj: 'mj'}, 'Hello']
// the function would return this, as a result:
// [1, 4, true, {mj: 'mj'}, 'Hello']
var compact = function (array) {
var truthyValues = [];
for (var i = 0; i < array.length; i += 1) {
if () {
truthyValues.push[i];
}
}
return truthyValues;
};
You're close. Here's what the if should be:
if (array[i]) {
truthyValues.push(array[i]);
}
Since you want to check for truthiness of each array element, just put array[i] in the if block. That gets the value of the array at i, and will evaluate as true if that value is truthy.
Then push not i - the index into array - but array[i], so that the actual value is in truthyValues.
Just put the value you want to check is truthy in the if statement, since the if statement checks for truthiness.
if(array[i]){
truthyValues.push(array[i]);
}
I think you can just use:
if (array[i]) { truthyValues.push(array[i]); }
Values like null will trigger false.
if (typeof array[i] !== "undefined" && array[i] !== null) {// push to array // }
most of these other answers will not work for falsy and existy values. You'll need to define what you intend to be existy and write a helper function for that. you could use the one I provided as a start and then roll your own.