I am trying to evaluate an array for uniformity. I.e. var num =[1,1,1,1,1,] // true or var num =[1,1,2,1,1] = //false. It could also be for an array of strings. What I am trying to do is evaluate the whole array and return a single "true" or "false". My code so far evaluates each item in the array and returns the result for each item. I'm very new to coding and taking classes online and working through problems without cheating!
var num = [1,1,3,1,1];
var first = num[0];
num.forEach(function (num, i) {
if(first === num){
console.log(true);
} else {
console.log(false);
}
});
You're on the right track. Instead of logging a true or false for each answer, create a variable to store the overall answer, then print that when you're done. Something like this:
var num = [1,1,3,1,1];
var first = num[0];
var ans = true;
num.forEach(function (n) {
if(first !== n){
ans = false;
}
});
console.log(ans);
Using .some()
var num = [1,1,3,1,1];
var notUni = num.some(function(val, idx, arr){
return val != arr[0]; // (If arr[0] (1) is the base you're interested in)
});
console.log( notUni ); // true
P.S: some will exit as soon it finds a (true) mismatch.
Use Array.prototype.every() function
var num = [1, 1, 3, 1, 1];
var result = num.every(n => n == num[0]);
The every() method tests whether all elements in the array pass the test implemented by the provided function.
var num = [1, 1, 1, 1, 1];
var result = num.every(n => n == num[0]);
document.write(result);
Related
I have this problem where I have a basic array containing numbers and I want to check if a certain number is in said array, and if it is, it returns the index where the number is. I get said number from a function. When I run the code, findIndex(<number>); gives me a typeError: <number> is not a function. Take a look at my code:
const numberProducer = function(n) {
return n + 1;
};
var number = numberProducer(1);
var arr = [1, 2, 3, 4];
var isNumberInArray = arr.findIndex(number);
if (isNumberInArray === -1) {
<do something>
}
else {
<do something>
}
I tried giving findIndex() a fixed value, and it still gives me the error.
findIndex takes function as an argument and return the first element which meets given condition. If you want to use findIndex() you need to pass a function
arr.findIndex(x => x === number);
But in this case the most suitable option is to use indexOf(). When there is no condition and you only want to get the index of element then indexOf() is better
arr.indexOf(number);
const numberProducer = function(n) {
return n + 1;
};
var number = numberProducer(1);
var arr = [1, 2, 3, 4];
var index = arr.indexOf(number);
console.log(index)
findIndex accepts a callback, not a number. Hence:
const isNumberInArray = arr.findIndex((x) => x === number);
Is what you want.
Because there is no function and condition in arry.findIndex(). findIndex() finds value when a value in the function at findIndex(). There should be parameter for a flag and a value for condition. For example,
arr.findIndex((value) => value === number);
Inside findIndex(), there is ES6 so it's same for the below
function(value) {
return value === number
});
function() { return } is same for () => {}. If the value meets number then findIndex returns index for the correct value.
Below it's reference of ES6
https://dev.to/sarah_chima/arrow-functions-in-es6-24
const numberProducer = function(n) {
return n + 1;
};
var number = numberProducer(1);
var arr = [1, 2, 3, 4];
//inside findIndex(), there should be function and condition
var isNumberInArray = arr.findIndex(
function(value) {
return value === number
});
console.log(number)
I tried to recursion those arrays to find odd/even numbers then push them to newArr but the result, not an array, that result is the string with numbers the result after found the odd/even numbers.
this is the code i wrote,
function odd(nums){
var result = [];
if(nums.length === 0) {
return result;
} else if (nums[0] % 2 === 0){
result.push(nums[0])
// return odd(nums.slice(1))
};
return result + odd(nums.slice(1));
};
var arr = [1,8,3,4,4,5,9,13,13,9,10];
var print = odd(arr);
console.log(print)
if i don't write return result + odd(nums.slice(1)); the result nothing / undefined,
can anyone help me to explain why that result in a string, not an array I wanted
You need to concat arrays. + does only work for strings or for numbers.
BTW, after block statements { ... }, you do not need a semicolon.
function odd(nums){
var result = [];
if (nums.length === 0) {
return result;
}
if (nums[0] % 2 === 0) {
result.push(nums[0]);
}
return result.concat(odd(nums.slice(1)));
}
var arr = [1, 8, 3, 4, 4, 5, 9, 13, 13, 9, 10];
var print = odd(arr);
console.log(print);
Recursion is probably a bad idea in JS, you should use it unless there is no better way to solve a problem. It will be slower and possibly result in overflow, if too many calls of recursive function is made.
To get the result you needed, it is better to use array filter method. It is clearer and faster.
var arr = [1,8,3,4,4,5,9,13,13,9,10];
var odd = arr.filter(n => !(n % 2))
console.log(odd)
As for the original question, I'd do it this way:
function odd(nums, result = []){
if (!nums.length) return result; // no need for else, this way clearer
if (nums[0] % 2 === 0) result.push(nums[0])
return odd(nums.slice(1), result)
};
var arr = [1,8,3,4,4,5,9,13,13,9,10];
console.log(odd(arr))
!!! Caution, next snippet WILL result in StackOverflow !!!
You may decrease array length to 10000 to check that it will work just fine.
function odd(nums, result = []){
if (!nums.length) return result; // no need for else, this way clearer
if (nums[0] % 2 === 0) result.push(nums[0])
return odd(nums.slice(1), result)
};
const arr = Array.from({length: 100000}, (_,i) => i)
const result = odd(arr)
console.log(`Array length: ${arr.length}`)
console.log(`Result length: ${result.length}`)
console.log(result.slice(0,5))
You could use concat method.
function odd(nums){
var result = [];
if(nums.length === 0) {
return result;
} else if (nums[0] % 2 === 0){
result.push(nums[0])
// return odd(nums.slice(1))
}
return result.concat(odd(nums.slice(1)));
}
var arr = [1,8,3,4,4,5,9,13,13,9,10];
var print = odd(arr);
console.log(print)
Another approach would be to pass the array containing the result as parameter, since it will be a reference, you don't have to return anything.
function odd(nums, result)
{
if(nums.length != 0)
{
if (nums[0] % 2 === 0)
{
result.push(nums[0]);
}
odd(nums.slice(1), result);
}
}
var arr = [1,8,3,4,4,5,9,13,13,9,10];
var result = [];
odd(arr, result);
console.log(result)
Instead of the concat you need in place of the string concatenation + you use now, better use filter
var odd = [],
even = [1,8,3,4,4,5,9,13,13,9,10]
.filter(function(x) { if (x % 2 === 0) return true; else odd.push(x) } );
console.log(odd,even)
Firstly, the .includes method does not work with my framework, so I omit this here.
I have checkIn(el,ar) function to check if el in ar like this:
function checkIn(el){
var check = false;
for (i = 0; i < ar.length; i++){
if(el === ar[i]){
check = true;
break;
};
};
return check;
};
it works normaly. Then I want to use the .every method to check if every element of a given array is in another given array
var x = [1,2,3];
var y = [1,2,3,4,5];
var check = x.every(checkIn(y))
check needs to be true, but it doesn't work?
.every accepts a callback for which the first parameter is an element of the array being iterated over. If you want to be able to use
x.every(checkIn(y))
then checkIn should return a function that can then be used as the callback:
function checkIn(containingArr) {
return item => containingArr.includes(item);
};
var x = [1, 2, 3];
var y = [1, 2, 3, 4, 5];
console.log(x.every(checkIn(y))); // every item in x is in y; true
console.log([0].every(checkIn(y))); // 0 is not in y; false
Or, to use something similar to your for loop:
function checkIn(ar) {
return el => {
var check = false;
for (i = 0; i < ar.length; i++) {
if (el === ar[i]) {
check = true;
break;
};
};
return check;
};
}
var x = [1, 2, 3];
var y = [1, 2, 3, 4, 5];
console.log(x.every(checkIn(y)));
console.log([0].every(checkIn(y)));
First off, your checkIn(el,ar) does only take el so if you're not getting an error you're accessing a global or out-of-scope variable ar that may hold data that doesn't make sense in that context.
If you simply want to check if an array contains a specific value there is a really simple way to do it:
[1,2,3].includes(3) //true
[1,2,3].includes(6) //false
And to extrapolate to a whole array using .every requires you to pass a lambda or function, not just a function call, like so:
var xs = [1, 2, 3];
var ys = [1, 2, 3, 4, 5];
xs.every(x => ys.includes(x))
where x => ys.includes(x) is shorthand for function(x){return ys.includes(x)}
or using your checkIn(el,ar)
xs.every(x => checkIn(x,ys))
Function checkIn looks redundant.
function checkIn(el, ar) {
let check = false;
for (let i = 0; i < ar.length; i++) {
if (el === ar[i]) {
check = true;
break;
};
};
return check;
};
Why not use Array.prototype.includes?
BTW, the first parameter of the function every should be a function but you pass the result of checkIn, which type is boolean.
We can do like this.
x.every((e) => y.includes(e))
I have an array and I want to remove all the string elements from it.
This is what I have so far. The result is not what I want since it returns only "bicycle"
Also, I am doing this in Test Complete so I need to have a main function that logs the result.
function ex06(){
var mailBox = "mailbox";
var twenty = 20;
var isItRaining = true;
var goat = "";
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = removeStrings();
Log.Message("stringsArray looks like this after the removal of all the string elements: " + result);
function removeStrings(){
var i;
var x
for(i = 0; i < stringsArray.length; i++){
if (typeof(stringsArray[i]) === 'string'){
x = stringsArray.splice(i, 1);
return x;
}
}
}
}
Version 1, with Array#filter
var a = [1, 2, "3", "4", true];
a = a.filter(function (e) {
return typeof e !== 'string';
});
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');
Version 2, with Array#splice and running backwards.
var a = [1, 2, "3", "4", true],
i = a.length;
while (i--) {
if (typeof a[i] === 'string') {
a.splice(i, 1);
}
}
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');
The Array.prototype.filter method is what you need:
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = stringsArray.filter(function(element) {
return typeof element !== 'string';
});
you need to reduce the counter variable and check the original array
try this simple example
var a = [1,2,"3", "4", true];
for( var counter = 0; counter < a.length; counter++)
{
if ( (typeof a[ counter ] ) == "string" )
{
a.splice(counter,1); counter--;
}
}
console.log(a); //output [1, 2, true]
try this code:
function ex06(){
var mailBox = "mailbox";
var twenty = 20;
var isItRaining = true;
var goat = "";
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = removeStrings();
Log.Message("stringsArray looks like this after the removal of all the string elements: " + result);
function removeStrings(){
var newarray = [];
var i;
var x
for(i = 0; i < stringsArray.length; i++){
if (typeof(stringsArray[i]) !== 'string'){
newarray.push(stringsArray[i]);
}
}
return newarray
}
}
JavaScript offers native methods to filter arrays, so that you can remove string elements more easily: Array.prototype.filter can make the process a lot easier (and prevents strange behaviours when using splice inside a loop).
function ex06(){
var mailBox = "mailbox";
var twenty = 20;
var isItRaining = true;
var goat = "";
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = removeStrings(stringsArray);
Log.Message("stringsArray looks like this after the removal of all the string elements: " + result);
function removeStrings(arrayWithString){
return arrayWithString.filter(function(item) {
return typeof item !== 'string'; // returns only items which are not strings
});
}
}
A small piece of advice: Pass in the array into your function instead of referencing it from the parent scope. This way you have a pure, reusable function (and no strange side effects you might not want).
I assume this is an exercise, and that's why you're not using Array#filter.
The problem is that you have your return x inside your for loop, so you return the first string you find.
You have at least three options:
Don't return anything, since removeStrings is modifying the original array. That one's easy: Just remove the return x; line.
Don't modify the original array; instead, create and return a new array with the strings left out. In that case, you'd start with x = [] before the loop, remove the splice call, and instead push any non-string onto x.
Modify the original array, and create and return a new array containing the strings you've removed. In that case, you'd remove return x from inside the loop, have x = [] before the loop, and push the entries you remove onto x. Then return x at the end.
In any of the places where you're modifying the original, note gurvinder372's point that when you remove an entry, you need to not increase the index counter, as you'll end up skipping the next entry.
I wouldn't do it the way he suggests, though; when I'm looping through an array modifying it, for isn't what I reach for, I reach for while:
i = 0;
while (i < stringsArray.length) {
if (typeof stringsArray[i] === 'string'){
stringsArray.splice(i, 1);
// We leave `i` alone here, because we need to process
// the new `stringsArray[i]` on the next pass
} else {
// Didn't remove this entry, move past it
++i;
}
}
Side note: typeof isn't a function, it's an operator, there's no need to put its operand in ():if (typeof stringsArray[i] === 'string'){
I have an array. I need to generate an alert if all the array items are 0.
For example,
if myArray = [0,0,0,0];
then alert('all zero');
else
alert('all are not zero');
Thanks.
You can use either Array.prototype.every or Array.prototype.some.
Array.prototype.every
With every, you are going to check every array position and check it to be zero:
const arr = [0,0,0,0];
const isAllZero = arr.every(item => item === 0);
This has the advantage of being very clear and easy to understand, but it needs to iterate over the whole array to return the result.
Array.prototype.some
If, instead, we inverse the question, and we ask "does this array contain anything different than zero?" then we can use some:
const arr = [0,0,0,0];
const someIsNotZero = arr.some(item => item !== 0);
const isAllZero = !someIsNotZero; // <= this is your result
This has the advantage of not needing to check the whole array, since, as soon it finds a non-zero value, it will instantly return the result.
for loop
If you don't have access to modern JavaScript, you can use a for loop:
var isAllZero = true;
for(i = 0; i < myArray.length; ++i) {
if(myArray[i] !== 0) {
isAllZero = false;
break;
}
}
// `isAllZero` contains your result
RegExp
If you want a non-loop solution, based on the not-working one of #epascarello:
var arr = [0,0,0,"",0],
arrj = arr.join('');
if((/[^0]/).exec(arrj) || arr.length != arrj.length){
alert('all are not zero');
} else {
alert('all zero');
}
This will return "all zero" if the array contains only 0
Using ECMA5 every
function zeroTest(element) {
return element === 0;
}
var array = [0, 0, 0, 0];
var allZeros = array.every(zeroTest);
console.log(allZeros);
array = [0, 0, 0, 1];
allZeros = array.every(zeroTest);
console.log(allZeros);
Use an early return instead of 2, 3 jumps. This will reduce the complexity. Also we can avoid initialisation of a temp variable.
function ifAnyNonZero (array) {
for(var i = 0; i < array.length; ++i) {
if(array[i] !== 0) {
return true;
}
}
return false;
}
Using Math.max when you know for certain that no negative values will be present in the array:
const zeros = [0, 0, 0, 0];
Math.max(...zeros) === 0; // true
No need to loop, simple join and reg expression will work.
var arr = [0,0,0,10,0];
if((/[^0]/).exec(arr.join(""))){
console.log("non zero");
} else {
console.log("I am full of zeros!");
}
Another slow way of doing it, but just for fun.
var arr = [0,0,0,0,10,0,0];
var temp = arr.slice(0).sort();
var isAllZeros = temp[0]===0 && temp[temp.length-1]===0;
you can give a try to this :
var arr = [0,0,0,0,0];
arr = arr.filter(function(n) {return n;});
if(arr.length>0) console.log('Non Zero');
else console.log("All Zero");