I can create like that code in js? if example == 0, 2, 4, 6, 8 { code here } else if { code here } I mean check example have one of this value
I dont wanna create many lines code example if == 0 , if == 2 ets
Thanks for help
I think what you want to do is compare your 'example' with each of the values.
let's assume your array is 2,4,6,8,0
then what you can do is
let example = 3;
let array = [2, 4, 6, 8, 10];
if (array.includes(example)) {
// true statement
} else {
// false statement
}
Just make a function and check the values via a loop and based on that return either false or true, look at the snippet below. The values should be in an array!
function checkValue(value){
for (let i of [0,2,4,6,8]){
if (i === value) {
return false;
}
}
return true;
}
console.log('3: ', checkValue(3));
console.log('8: ', checkValue(8));
Alternatively if you want to see if the value is an odd number or not, you can use the remainder operator:
let i = 3;
console.log(i%2 === 1)
Related
I would like to check if an element inside an array is another array. I'm solving a code challenge where the problem is iterating through an array and checking for a 7 but if an
element is an array I would like to continuously check each nested array for a 7.
I have console.log() in my first 'if' statement and I've seen that sevenBoom() is being called more than once. But for some reason it's not returning 'Boom!'
SevenBoom should return 'Boom!' if there's a seven.
function sevenBoom(arr) {
if (arr.includes(7)) {
return "Boom!";
}
arr.forEach((val) => {
if (Array.isArray(val)) sevenBoom(val);
});
}
sevenBoom([1, 3, 4, 6, [7]) // Returns undefined
sevenBoom([3, 7, 8, 9]) // Returns 'Boom!'
You could take a boolean value as result and use Array#some for checking arrays.
function hasSeven(array) {
function seven(a) {
return a.includes(7) || a.some(v => Array.isArray(v) && seven(v));
}
return seven(array)
? 'Boom!'
: 'There is no 7';
}
console.log(hasSeven([7]));
console.log(hasSeven([[7]]));
console.log(hasSeven([[[7]]]));
console.log(hasSeven([]));
console.log(hasSeven([[]]));
console.log(hasSeven([[[]]]));
const sevenBoom = (arr) => {
const recurse = (arr) => arr.some(n => Array.isArray(n) ? recurse(n) : n === 7);
if (recurse(arr)) {
return 'Boom';
}
}
This is assuming what should be returned other than 'Boom' is void. It's a bit of an awkward place for recursion since you want to return a string if you meet some criteria and nothing otherwise.
Firstly you need to return the value from your second if condition too.
But forEach() cannot be interrupted (for ex: with a return statement) and will run for all items. So you can keep track using a flag variable outside the forEach() and return your result on that basis.
function sevenBoom(arr) {
if (arr.includes(7)) {
return "Boom!";
}
let found = false;
arr.forEach((val) => {
if (Array.isArray(val)) if(sevenBoom(val)) found="Boom!";
})
return found;
}
console.log(sevenBoom([1,2,3]));
console.log(sevenBoom([1,2,7]));
console.log(sevenBoom([1,2,[2,7]]));
console.log(sevenBoom([1,2,[2,3,[4,5]]]));
console.log(sevenBoom([1,2,[2,3,[4,7]]]));
Note: How sevenBoom() can be directly used inside an if statement. This is because of the concept of truthy and falsy values.
PS: As mentioned above, forEach() will run for all items, no matter what. You can use any other looping mechanism like a simple for loop, some() etc. I just copied your code and hence used forEach()
I would check if an element is seven in the same loop that you are checking if an element is an array that way you can avoid going through the array unnecessarily.
const sevenBoom = arr => {
for (const ele of arr) {
if (ele === 7) return 'Boom';
if (Array.isArray(ele)) {
//this prevents you from halting your function early
//you only want to return in the loop if a 7 is found
if (boom(ele) === 'Boom') return 'boom'
}
}
}
You can use the .flat(depth) method to flatten each array before using the .includes() method. Choose a depth that would cover all possible arrays for your project.
function sevenBoom(arr) {
return arr.flat(10).includes(7) ? 'Boom!' : '-'
}
DEMO
let a = [1, 3, 4, 6, [7]],
b = [3, 7, 8, 9],
c = [1,2,[5,6,[3,5,[7,6]]]],
d = [0],
e = [1, [5, 4], 3, 5, [7]];
function sevenBoom(arr) {
return arr.flat(10).includes(7) ? 'Boom!' : '-'
}
for(let arr of [a,b,c,d,e]) {
console.log( sevenBoom( arr ) );
}
console.log( e ); //Original array remains unchanged
If 7 is not present in the root array, then your function isn't returning anything.
Try this, just a minor refactoring:
function sevenBoom(arr) {
if (arr.includes(7)) return 'Boom!';
for (let val of arr) {
if (Array.isArray(val)) {
if (sevenBoom(val)) return sevenBoom(val);
}
}
return false;
}
I have a problem to solve in ELOQUENTJS book, can somebody help and tell me what's wrong in this code.
This is my code so far.
function every(array, test) {
for (let i of array) {
let curArr = array[i];
if (test(curArr)) {
return true;
} else {
return false;
}
}
}
console.log(every([1, 3, 4, 12], n => n < 10));
// returns true
I'm expecting to see false as a return, but somehow it returns true.
Your first issue is with your return true. This line will make your function "exit", thus stopping any of the remaining code from executing. As 1 < 10, you are immediately returning true from your function. Instead, you can return true only once you have checked every element.
Your other issue is that a for..of loop will get every element in your array, not every index like you think you're doing so i infact actually is equal to your curArr variable:
function every(array, test) {
for(let curArr of array){
if(!test(curArr)){
return false;
}
}
return true;
}
console.log(every([1, 3, 4, 12], n => n < 10));
I'm a complete newbie to programming and mathematical concepts (took Math 101 in college) so I'm struggling with this problem:
Write a function that takes in a number, and returns an array with that number in it that many times.
Here's the code I've got so far:
function numReturn(x) {
var newArray = [];
if (typeof x === "number") {
return newArray.push[x]* x;
} else {
return null;
}
}
Here's my thought process:
Create a function that can take in a number, x.
Within that function, create a blank array so you can push values to it later.
Check if the typeof value entered in for x is a number. If it is, return it pushed to the end of the blank array. Otherwise, return null.
When I put this in the Javascript console and plug a value in, it comes back undefined. Anyone have some pointers for me?
function a(i) {
var a = new Array(i);
return a.fill(i);
}
or return new Array(i).fill(i);, for short. Test:
a(4)
// --> [4, 4, 4, 4]
Array.prototype.fill() is an ES6 method and is not yet universally implemented. Chrome and Firefox have it, IE does not - but there is a polyfill available.
Compare: http://kangax.github.io/compat-table/es6/#test-Array.prototype_methods_Array.prototype.fill
In order to do something an arbitrary number of times, one uses a loop. There are several loops, but here the for loop is most appropriate.
A for loop has the following structure:
for(var i = 0; i < x; i++) {
// ^initializer
// ^condition
// ^increment
//body
}
The initializer is the first thing that is done when entering the loop. IN this case, it means a variable named i is set to 0. Then the condition x is checked. If the condition i < x holds, the loop is executed: the body is executed. After the body is executed, the increment is performed (here i++), and then the condition is rechecked, if the condition still holds, the loop is executed again, and so on.
You can apply this concept as follows:
function numReturn(x) {
var newArray = [];
if (typeof x === "number") {
for(var i = 0; i < x; i++) {
newArray.push(x);
}
return newArray;
} else {
return null;
}
}
This: newArray.push[x]* x does not push x times. The * operator just multiplies numbers, always and only. You want to push x times, so use a for like this:
for (var i = 0; i < x; i++ )
newArray.push(x);
and then return newArray.
Taking from answer of Most efficient way to create a zero filled JavaScript array?
function numReturn(x){
return Array.apply(null, Array(x)).map(Number.prototype.valueOf,x);
}
console.log(numReturn(10)); // [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
var n = 7
var result = Array.apply(null, {length: n}).map(function(){return n})
// Demo output
document.write(JSON.stringify(result))
As function:
function numReturn(x) {
if (typeof x === "number") {
return Array.apply(null, {length: n}).map(function(){return n})
} else {
return null;
}
}
I have 2 JS arrays and I am iterating through both of them to find similar ones.
anomalies.forEach(function(anomaly) {
links.forEach(function(link) {
if ((link.source.name === anomaly.source) && (link.target.name === anomaly.target)) {
console.log("anomaly");
link.type = "anomaly";
console.log(link);
} else {
link.type = "normal";
}
});
});
console.log(links);
In a case where the value of link.type should be "anomaly", still its reflecting to be "normal".
Why is it so and what should be done?
I was an algorithmic mistake. In the provided screenshot type="normal" is the current value of the object.
Consider:
Loop1
Loop2
condition
if the condition inside loop2 is met for the link object then its type value is assigned "anomaly". But when the next iteration of loop1 occurs, and the condition is not met for the same link object, then the value is assigned "normal". Hence its an algorithmic mistake.
Looks, like each does not change start value, try that:
n = anomalies.length;
k = links.length;
for(i=0; i<n; i++){
for(j=0; j<k; j++){
if ((links[j].source.name === anomalies[i].source) && (links[j].target.name === anomalies[i].target)) {
console.log("anomaly");
links[j].type = "anomaly";
console.log(links[j]);
} else {
links[j].type = "normal";
}
}
}
console.log(links);
If you take a look at the documentation:
here
You can see that there is 3 arguments can be passed to the callback function
- element
- index
- array
If you call forEach like this:
var x=[1,2,3,4,6];
x.forEach(function(e){
if(e==3)f=9;
console.log(e);
})
console.log(x);
1
2
9
4
6
[1, 2, 3, 4, 6]
The value of the array element will not change because you are changing a buffers value.
But if you use forEach like this:
var x=[1,2,3,4,6];
x.forEach(function(e,i,a){
if(e==3)a[i]=9;
console.log(a[i]);
})
console.log(x);
1
2
9
4
6
[1, 2, 9, 4, 6]
you see that the value changed in the array.
Take the following piece of code:
var testArr = [1, 2, 3, 4, 5];
function check(num) {
if (num !== undefined) {
if (num in testArr) {
alert("in");
} else {
alert("not in");
}
}
}
With the check() function I try to check whether a given parameter is part of the testArr array or not.
In general the function works fine, only when checking for 0 the condition is met, although 0 is not part of the array. See for yourself: Fiddle
Why is this happening?
One possible solution I could think of is that 0 is evaluated as false in some cases (== vs ===), but when passing false as argument, the condition is not met, which does not make any sense to me – I am puzzled.
In this case you returned that the index exists in the array but not the value. See this documentation in operator. I think that you must validate values of array with indexOf function.
You want to use the [].indexOf(elem) (doc) and check for -1 if it's not in the array. There's also a few other ways mentioned in this question How do I check if an array includes an object in JavaScript?
Your code would be updated as follows:
var testArr = [1, 2, 3, 4, 5];
function check(num) {
if (num !== undefined) {
if (testArr.indexOf(num) != -1) {
alert("in");
} else {
alert("not in");
}
}
}
The in operator searches for keys and 0 will be a valid index in any nonempty array. in does not return true for all arrays. Try it with an empty array []
"in" is checking by key.
You have testArr[0] so you can get alert("in").
That is, if u use check(0)~check(4) will be alert("in"),
other will be alert("not in") such as check(5).
var testArr = [1, 2, 3, 4, 5];
function check(num) {
if (num in testArr) {
return "check(" + i + ") = in ";
} else {
return "check(" + i + ") = not in ";
}
}
for (var i = 0; i <= 6; i++) {
document.write(check(i) + "<br>")
}
The prop parameter from the in operator will search a property or check if an index exists.
From the documentation:
prop: A string or numeric expression representing a property name or
array index.
And from one of it's examples:
You must specify the index number, not the value at that index.
If you do:
<script>
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
'length' in trees // returns true because length is a property.
</script>
So in your case you are asking the check function if index 0 exists.