How to get an isolated value from an array using JavaScript map? - javascript

When I execute the below script, I get an array of values; how to get the value '3' separately out of an array. I use JS map here.
function value() {
return dataLayer.map(function(item, index)
{
return (item.event == 'impressionOnScroll' ? index : false);
})
};
value();

You can e.g. use Array#filter to get only the number-ish values.
var arr = [false, false, false, 3, false];
console.log(arr.filter(Number));
//or
//this will work also for 0
console.log(arr.filter(v => typeof v == 'number'));

Array.prototype.filter runs a function against every value in an array. If you return a truthy value from the array, it is kept. Otherwise, it is discarded.
Here you should check to see if the value is not false:
function value() {
return dataLayer.map(function(item, index)
{
return (item.event == 'impressionOnScroll' ? index : false);
}).filter(value => value !== false);
};

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

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.

Polyfill for object.value to return truthy assertion

My original task was to create a function that returned a boolean value if my data object contained a truthy value.
I do not care what value or key is truthy, only that the data contains a truthy value.
var fruits = { apples: false, oranges: true, bananas: true }
When iterating over this object the return should be true because there are true values within.
The following function did work:
return Object.values(fruits).some(function(k) {
return k;
});
However I cannot use Object.value nor the array.some due to IE compatibility
The suggested Polyfill is to use .map instead to get each value, however but the next step is removing .some() - I have tried using .filter() but this takes me back to the original problem that it returns the key that is truthy not merely an assertion that a truthy value exists in the databaset
If you need old-style JavaScript, then just go for a plain for loop:
function hasTruthy(fruits) {
for (var key in fruits) {
if (fruits.hasOwnProperty(key) && fruits[key]) return true;
}
return false;
}
You don't even need that hasOwnProperty check.
var fruits = {
apples: false,
oranges: true,
bananas: true
}
function hasTruthyValue(obj) {
for (let key in obj) {
if (obj[key]) {
return true;
}
}
}
console.log(hasTruthyValue(fruits)); //true

if any item in array === x then return false

var array = [false,true,true,true,true];
I would like to return false if any item in array is false and only return true if all items are true. is there a fast way to do this with out all the boilerplate? in python i would use the "if is in" syntax.
In your case you'd use the every() method. The method expects every return value in each iteration to evaluate to true so simply passing the current value, which all happen to be a booleans will suffice without any additional logic.
var array = [false, true, true, true, true].every(bool => bool);
console.log(array);
Option 1: You can use .indexOf(). This example will return false if myArray contains false, and return true otherwise:
function hasNoFalse(myIndex) {
return myArray.indexOf(false) === -1;
}
Option 2: You can use .some() or .every() :
I would like to return false if any item in array is false
return myArray.some((val) => val === false)
and only return true if all items are true.
return myArray.every((val) => val === true)
you can use .indexOf(element) and if the result is greater than -1, then there's that element in the array
While everyone is using arrow function, this is one way to do it without it
function myFunction(array) {
var b = 0;
array.forEach(function(element) {
if(element)
b++
});
if(b == array.length)
return true;
else
return false;
}
I wrote this only for people who don't know what arrow is.
a.every(function(val){
return val == true;
});
Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

How to determine equality of values of JavaScript object?

In the given object all values of properties are the same.
var obj = {
property1: 'Some Value',
property2: 'Some Value',
property3: 'Some Value',
property4: 'Some Value'
}
The function checkEquality should return true if all values are the same and false otherwise.
I can do the following to achieve it:
function checkEquality () {
var compare = obj.propery1;
for (var key in obj) {
if (obj[key] !== compare) {
return false;
}
}
return true;
}
But this solution by far not the best.
You could use Array#every for it.
The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
var obj = { propery1: 'Some Value', propery2: 'Some Value', propery3: 'Some Value', propery4: 'Some Value' },
equal = Object.keys(obj).every(function (k, i, kk) {
return !i || obj[kk[0]] === obj[k];
});
console.log(equal);
Great answer by #Nina, I'd just like to add something different using reduce and ES6 syntax:
const sameValues = (obj ) => {
let keys = Object.keys( obj );
let initial = obj[ keys[0] ];
// val will be either the initial value or false
let val = keys.reduce( (prev, cur) => ( obj[cur] === prev ? prev : false ), initial );
return val === initial;
}
https://jsfiddle.net/9tb5mdoL/

Categories

Resources