This question already has answers here:
Javascript - check array for value [duplicate]
(3 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
In Javascript, how can I ensure that the array of ages has both ages 10 and 18 and not just one.
var ages = [3, 10, 18, 20];
ages.filter(age => age === 10 || age === 18); // returns 10 and 18
ages.filter(age => age === 10 && age === 18); // returns null
The && doesn't ensure that both exist, as it returns null. I know I can use 2 different ages.find/filter and check the combined result, but I am wondering if there is a more elegant way of doing this in a single statement.
To clarify, in the ages array, if I check for 10 (exists) and 21 (doesn't exist), it should return null or false, as one of them does not exist.
You have to use includes function:
var ages = [3, 10, 18, 20];
console.log(ages.includes(10) && ages.includes(18));
Another method is to use indexOf method:
arr.indexOf(searchElement)
arr.indexOf(searchElement, fromIndex)
var ages = [3, 10, 18, 20];
console.log(ages.indexOf(10)!=-1 && ages.indexOf(18)!=-1);
findIndex is another method that you can use.It actions like indexOf, but there are some differences:
Array.prototype.indexOf() expects a value as parameter. This is usefull for arrays of primitive types,such as Number, String, Boolean.
Array.prototype.findIndex() have a callback function as first parameter. This is usefull specially when you have array of objects.
var ages = [3, 10, 18, 20];
var bool=ages.findIndex(a=>a==10)!=-1 && ages.findIndex(a=>a==18)!=-1;
console.log(bool);
Related
This question already has answers here:
How does the function in this array filter work?
(2 answers)
Closed 1 year ago.
There is a function designed to clear an array of duplicate characters
let x = [55, 44, 55, 30, 30]
let unique = x.filter((e, i) => x.indexOf(e) === i )
console.log(unique)
The first value of the filter is responsible for the current processed element in the array, the second is the index of the current processed element in the array, as far as I understand, in the function we use indexOf, we compare two indices of the same number (indexOf (e) and i), but how -that way to filter the array, we still get it, how?
indexOf documentation says:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
This is what you'll see in the execution:
e=55, i=0: indexOf(55) is 0 === 0: true!
e=44, i=1: indexOf(44) is 1 === 1: true!
e=55, i=2: indexOf(55) is 0 !== 2: false!
e=30, i=3: indexOf(30) is 3 === 3: true!
e=30, i=4: indexOf(30) is 3 !== 4: false!
Your output will only include the true results, after items 2 and 4 are removed:
[55, 44, 30]
indexOf always returns the index of the first appearance of your input. This is why this filter function works.
In the case of your example, let x = [55, 44, 55, 30, 30], x.indexOf(55) would yield 0. Do you see why this filters out any other occurrences of 55?
This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 1 year ago.
If I have an Array of some numbers.
Ex. var num =[123, 234, 12, 0, 23, 19];
How can I get a total of all these elements = 411;
Try This, it is the most recommended method to use.
Even in SAP -Fiori standard code, this method is used.
var num =[123, 234, 12, 0, 23, 19];
var total = num.reduce((a, b) => a + b, 0);
This question already has answers here:
Parameters inside callback function in Javascript
(1 answer)
Higher-Order Functions in JS
(1 answer)
How is this method using a parameter that is never given a value? [duplicate]
(1 answer)
Closed 2 years ago.
I highlighted the parameter that I don't understand where its value comes from. Shouldn't the array get passed? it makes no sense. It all feels backwards. How does the array values get into the ages.some(checkAdult) invocation? Does the keyword before the dot become the argument that I imagine should be in parenthesis after checkAdult?
Why doesn't it go some(checkAdult(ages))?
Why append it to the end of something with a dot?
var ages = [3, 10, 18, 20];
function checkAdult(age) { // THIS LINE HERE, how does it link to the array???
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.some(checkAdult);
}
<p>Click the button to check if any of the elements in the array has a value of 18 or more.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Typically (but not always) the user-supplied function is called by the higher-order function.
In the example below, some, calls f with each element of t, until the first truthy result is found. Otherwise a false result is returned.
const some = (f, t) =>
t.length === 0
? false
: Boolean(f(t[0])) // f gets called by some
|| some(f, t.slice(1))
console.log(some(v => v > 30, [ 10, 20, 30, 40 ]))
// true
console.log(some(v => v > 99, [ 10, 20, 30, 40 ]))
// false
Or an iterative version of the same program -
function some (f, t)
{ for (const v of t)
if (Boolean(f(v)))
return true
return false
}
console.log(some(v => v > 30, [ 10, 20, 30, 40 ]))
// true
console.log(some(v => v > 99, [ 10, 20, 30, 40 ]))
// false
This question already has answers here:
Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
(88 answers)
Closed 4 years ago.
Is it any way to create an array a selected size(for example 10) and immediately on the spot fill in it with some numbers specified pattern (1, 2, 3, OR 2, 4, 6 and so on) in one statement in JS?
let arr = new Array(10).fill( (a) => {a = 1; return a++; } );
console.log(arr); // Should be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
In other words can I pass a some patern or function to method fill insted of a single value.
Actually there's much nicer idiom to create ranges: a spreaded Array constructor:
[...Array(n)]
creates an array of n undefined values. To get 0..n-1, just pick its keys:
[...Array(n).keys()]
for arbitrary ranges, feed it to map:
r = [...Array(10)].map((_, i) => i + 1)
console.log(r)
see here: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?
old answer:
yep, you're looking for Array.from:
r = Array.from({length: 10}, (_, i) => i + 1);
console.log(r)
How does this work? .from inspects its first argument (which can be any object) and picks its .length property. Then, it iterates from 0 to length - 1 and invokes the second argument with two parameters - a value (which is undefined unless the first argument contains a corresponding numeric property) and an index, which takes values from 0...length-1. In this example, we have a function that just returns an index + 1, thus giving us 1..length.
Here's a useful wrapper for the above:
let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);
console.log(range(1, 10))
For ES5, the idiom is Array.apply(null, {length:N}):
r = Array.apply(null, {length: 10}).map(function(_, i) {
return i + 1
})
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Return array value with forEach() [duplicate]
(1 answer)
Closed 5 years ago.
So there are a lot of questions about iterating over an array, but I found none that says how to get the transformed array back as the left side variable. I can always do a standard for loop with indicies but I was wondering if I could use something like a .foreach that would return a transformed array.
Psedo example: I have an array points which are made up of an object Phaser.Point
Such that I can write the following code
x = new Phaser.Polygon(points.foreach(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
new Phaser.Polygon takes an array of Phaser.Point objects
In this case, you may want to use Array.prototype.map(). Here is an example from MDN:
var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
In your case:
x = new Phaser.Polygon(points.map(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
References:
Array.prototype.map()
You can use Array.map. Array.map returns new array.