how can I go through a list and make the computer check if it's a number, if it is a number, I want to count and move on until the end and then show the result.
for example if I had an array:
var myArray = [1,2,a,4];
What I did was I would first split my array:
var splitted = myArray.toString()split(",").join(" ");
and then I used the for loop to go through each splitted value and count it if it is a number(or a string) and then show the result in a the appropriate box:
for(i=0;i<splitted.length; i+=1)
{
if(isNaN(splitted[i])===true)
{
document.getElementById("resultWordCount").value = splitted[i];
}
else
{
document.getElementById("resultNumberCount").value = splitted[i];
but with this code I keep getting the last number that appears in my list and the last string that appears in my list to show up as a result in my boxes. What can I do to fix this?
You could check with isNaN and count.
var myArray = [1, 2, 'a', 4],
result = myArray.reduce(function (s, a) {
return s + !isNaN(a);
}, 0);
console.log(result);
var myArray = [1,2,a,4];
var result = 0;
for(var i=0; i < myArray.length; i++) {
result += !isNaN(+myArray[i]) ? myArray[i] : 0;
}
var count = 0;
myArray.forEach(function(item){
if(!isNaN(Number(item))){
count ++;
}
});
console.log(count);
first, if you already have an array, why would you transform it into a string, then split it, then join it again to another string? you're not looping over the array items but over the string characters. this will lead to all sorts of problems when your input changes.
then, isNaN(splitted[i])===true checks if the current item of the array is NOT a number, so you should ignore those instead of using them.
finally, you're not doing any sum anywhere, just assigning each item in turn to the value of the "resultNumberCount" tag. That's why, at the end of the process you just see whatever value was last in the array (or, actually, string)
You can use map function to count number of integers
var myArray = [1, 2, 'a', 4];
var numbers = 0;
myArray.map(function (a) {
if (Number(a))
numbers++;
});
console.log(numbers);
You can do:
var a = [1, 2, 'c', 4];
console.log(a.filter(function(value){
return !isNaN(value);
}).length)
You dont have to split your array
And just concatenate the values
var myArray = [1,2,"a",4];
var countNum = 0;
var countNaN = 0;
for(i=0;i<myArray.length; i+=1){
if(isNaN(myArray[i])){
document.getElementById("resultWordCount").value += myArray[i];
countNaN++;
}else{
document.getElementById("resultNumberCount").value += myArray[i];
countNum++;
}
}
console.log(countNaN);
console.log(countNum);
<input id="resultNumberCount" type="text" disabled >
<input id="resultWordCount" type="text" disabled >
EDIT:
If you want only the total:
var myArray = [1,2,"a",4];
var countNum = 0;
var countNaN = 0;
for(i=0;i<myArray.length; i+=1){
if(isNaN(myArray[i])){
countNaN++;
}else{
countNum++;
}
}
document.getElementById("resultNumberCount").value = countNum;
document.getElementById("resultWordCount").value = countNaN;
console.log(countNaN);
console.log(countNum);
<input id="resultNumberCount" type="text" >
<input id="resultWordCount" type="text" >
Related
I've got a assignment to make function that gives you a sorted array with 6 random numbers from 1 to 45. None of the array values should equal to one another.
I thought about a solution that would work in Java but the JavaScript console logs I get are pretty confusing. Could anyone help me out?
"use strict";
var numbers = [];
for(var x = 1; x <46;x++){
numbers.push(x);
}
function LottoTipp(){
var result = [];
for(var i = 0; i <6; i++){
var randomNum = Math.round(Math.random()* 45);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum)
}
return console.log(result) + console.log(numbers);
}
LottoTipp();
the console logs
[ 34, 7, undefined, undefined, undefined, undefined ]
[ 1, 2, 3, 4, 5, 6 ]
There were three problems:
If you want to remove one item of an array you have to splice it by the items index and give a deletecount.
In your case: numbers.splice(randomNum, 1);
You have to use Math.floor instead of Math.round, because Math.floor always down to the nearest integerer, while Math.round searches for the nearest integer wich could be higher than numbers.length.
After removing one item the length of the array has been changed. So you have to multiply by numbers.lenght instead of 45.
In your case: var randomNum = Math.floor(Math.random()* numbers.length);
"use strict";
var numbers = [];
for(var x = 1; x < 46; x++){
numbers.push(x);
}
function LottoTipp(){
var result = [];
for(var i = 0; i < 6; i++){
var randomNum = Math.floor(Math.random()* numbers.length);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum, 1);
}
return console.log(result) + console.log(numbers);
}
LottoTipp();
If you only want an array with random unique numbers I would suggest doing it like this:
<script>
var array = [];
for(i = 0; i < 6; i++) {
var number = Math.round(Math.random() *45);
if(array.indexOf(number) == -1) { //if number is not already inside the array
array.push(number);
} else { //if number is inside the array, put back the counter by one
i--;
}
}
console.log(array);
</script>
There is no issue with the console statement the issue is that you are modifying the numbers array in your for loop. As you are picking the random number between 1-45 in this statement:-
var randomNum = Math.round(Math.random()* 45);
and you expect that value would be present in the numbers array at that random index. However you are using array.splice() and providing only first parameter to the function. The first parameter is the start index from which you want to start deleting elements, find syntax here. This results in deleting all the next values in the array.Therefore if you pick a random number number say.. 40, value at numbers[40] is undefined as you have deleted contents of the array.
if you want to generate unique set of numbers follow this post.
hope it helps!
Just add the number in the result if it is unique otherwise take out a new number and then sort it. Here is an implementation:
let result = []
while(result.length < 6) {
let num = Math.round(Math.random() * 45);
if(!result.includes(num)) {
result.push(num);
}
}
result.sort((a,b) => {
return parseInt(a) - parseInt(b);
});
console.log(result);
I have some logic within an app that generating strings like the following:
"001"
"021"
"031"
I want to take the single string and split this and add the numbers in a basic efficient manner.
e.g for the second string above
021 - desired outcome would be split this to make the sum 0 + 2 + 1 = 3 - how do I split the string by each number using vanilla javascript?
Try this:
var array = "0123456";
var result = array.split("").reduce((acc, cur) => {return (+acc) + (+cur);},0);
console.log(result);
As Bucket said in the comments, this will split the string up into characters, then use array.reduce() to merge all the characters into one value by using an arrow function that converts them to numbers and sums them.
var str = "021";
var a = str.split(""); // converts the string into an array
var result = a.reduce((i, n) => {
return Number(i)+ Number(n)
},0);
console.log(result)
//result = 3
This is probably as efficient as you can possible make it, but it does not do any input validation:
var input = "0021031";
var zeroCode = "0".charCodeAt(0);
function sum(input) {
var result = 0;
for (var i = 0; i < input.length; ++i) {
result += input.charCodeAt(i) - zeroCode;
}
return result;
}
console.log(sum(input))
function mathAdd(s) {
// take input and split it by ''
// use a as the accumulator
// use v as the value
// add the value to the accumulator and start at 0
// return the value
return String(s).split('').reduce((a, v) => a + parseInt(v, 10), 0);
}
console.log(mathAdd("001"));
console.log(mathAdd("021"));
console.log(mathAdd("031"));
var result = 0;
var second = "021";
var arr = second.split("");
for(var i = 0; i < arr.length; i++)
result = +arr[i] + result;
console.log(result);
Adding Numbers in a String :-
function addNum(nums) {
let newnums = nums.split(',').map(Number);
sum = 0;
for(i=0; i<newnums.length; i++) {
sum = sum + newnums[i];
} return sum;
}
console.log(addNum("1, 2, 3, 4, 5, 6, 7"))
Beginner programmer here. I'm struggling with an assignment that's taking input text, splitting the words into single array items and then listing the total number of each words in an output. The splitting of the input works fine, but I need to check the array for duplicate items and remove that item (need to keep it unique) while also increasing the count on that particular word.
The idea was to make an array consisting of the words alone, and another that keeps track of the count. Glad to receive tips to use a simpler approach as well.
And yes, I know there is several solutions to this problem on SO, but I dont quite understand how to fix this particular code using functions.
function gen()
{
var arr = [];
var counter = [];
var str = document.getElementById("inpTxt").value;
str.toString();
str = str.split(" ");
for(var i = 0; i < str.length; i++)
{
arr.push(str[i]);
counter[i]++; //ignore that this array hasnt been properly declared yet, Im trying to make this equal length of arr with default value 0
//tried nested loop here for making comparison, didnt work
document.getElementById("print").innerHTML += "Total number of the word \"" + arr[i] + "\": " + counter[i] + " <br />";
}
}
If you're using ECMAScript2015(ES6), you can build a Set - which guarantees unicity - from your array :
var inputArray = [1, 1, 2, 3, 2, 4, 5, 5, 4, 1];
console.log(new Set(inputArray)) // displays Set { 1, 2, 3, 4, 5 }
Otherwise, you can loop over the array and check if a particular element follows another occurrence of itself :
var inputArray = [1, 1, 2, 3, 2, 4, 5, 5, 4, 1];
// with ES6 :
var result = inputArray.filter((element, index) => ! inputArray.slice(0, index).includes(element));
// without ES6 :
result=[];
for (var i=0; i<inputArray.length; i++) {
var currentElement = inputArray[i];
var previouslyFound = false;
for (var j=0; j<i && !previouslyFound; j++) {
previouslyFound = inputArray[i] == inputArray[j];
}
if (!previouslyFound) result.push(currentElement);
}
However, since we are looping over the array, it would be as fast to count the occurrences without unicizing the array first :
var inputArray = [1, 1, 2, 3, 2, 4, 5, 5, 4, 1];
// with ES6 :
var result = inputArray.reduce(function(map, element) {
map[element] = map.hasOwnProperty(element) ? map[element] + 1 : 1;
return map;
}, {});
// without ES6 :
var result = {};
for (var i=0; i<inputArray.length; i++) {
var currentElement = inputArray[i];
if (result.hasOwnProperty(currentElement)) {
result[currentElement] = result[currentElement] + 1;
} else {
result[currentElement] = 1;
}
}
Try the indexOf method of arrays to figure out whether you already have the string in array.
function gen()
{
var arr = [];
var counter = [];
var str = document.getElementById("inpTxt").value;
str.toString();
str = str.split(" ");
for(var i=0; i < str.length; i++)
{
if(arr.indexOf(str)==-1){
arr.push(str[i]);
counter[i]++; //ignore that this array hasnt been properly declared yet, Im trying to make this equal length of arr with default value 0
}
//tried nested loop here for making comparison, didnt work
document.getElementById("print").innerHTML += "Total number of the word \"" + arr[i] + "\": " + counter[i] + " <br />";
}
}
PS: please know that there are less expensive methods available out there but i am just trying to help with whatever i can.
Ok, this might be easy for some genius out there but I'm struggling...
This is for a project I'm working on with a slider, I want an array the slider can use for snap points/increments... I'm probably going about this in a mental way but its all good practice! Please help.
var frootVals = [1,2,3,4,5];
var frootInc = [];
for (i=0; i<=frootVals.length; i++) {
if (i == 0){
frootInc.push(frootVals[i]);
}
else{
frootInc.push(frootInc[i-1] += frootVals[i])
}
};
What I'm trying to do is create the new array so that its values are totals of the array elements in frootVals.
The result I'm looking for would be this:
fruitInc = [1,3,6,10,15]
For a different take, I like the functional approach:
var frootVals = [1,2,3,4,5];
var frootInc = [];
var acc = 0;
frootVals.forEach(function(i) {
acc = acc + i;
frootInc.push(acc);
});
var frootVals = [1,2,3,4,5]
, frootInc = [];
// while i < length, <= will give us NaN for last iteration
for ( i = 0; i < frootVals.length; i++) {
if (i == 0) {
frootInc.push(frootVals[i]);
} else {
// rather than frootIne[ i-1 ] += ,
// we will just add both integers and push the value
frootInc.push( frootInc[ i-1 ] + frootVals[ i ] )
}
};
There were a few things wrong with your code check out the commenting in my code example. Hope it helps,
This will do:
var frootVals = [1,2,3,4,5];
var frootInc = [];
for (i=0; i < frootVals.length; i++) { // inferior to the length of the array to avoid iterating 6 times
if (i == 0) {
frootInc.push(frootVals[i]);
}
else {
frootInc.push(frootInc[i-1] + frootVals[i]) // we add the value, we don't reassign values
}
};
alert(JSON.stringify(frootInc));
jsfiddle here: http://jsfiddle.net/f01yceo4/
change your code to:
var frootVals = [1,2,3,4,5];
var frootInc = [frootvals[0]]; //array with first item of 'frootVals' array
for (i=1; i<frootVals.length; i++) {
frootInc.push(frootInc[i-1] + frootVals[i]); //remove '='
}
Here's a very simple pure functional approach (no vars, side-effects, or closures needed):
[1,2,3,4,5].map(function(a){return this[0]+=a;}, [0]);
// == [1, 3, 6, 10, 15]
if you name and un-sandwich the function, you can use it over and over again, unlike a hard-coded var name, property name, or for-loop...
I have 2 arrays that I need to compare against each other and return the count of the same.
Example: compare array1 [abcd] against array2 [adce]. Return would be 2,1 as both a and c are in same position and d is in the wrong position.
function () {
var index = 0;
for (index = 0; index < length; index++) {
if (array1[index] == array2[index]) {
count++
}
}
return count
}
I'm getting a return of 1. I think that's because they equal in length that is why I'm getting a 1. So I'm thinking that I now need to put another for loop and have that loop go through the elements individually, but not sure how to do this. I could be completely wrong in what I have put above, if so, could someone explain the process to me please.
You get 1 as output because length is not defined in your code
var array1 = ['a','b','c','d'];
var array2 = ['a','d','c','e'];
var length = Math.min(array1.length,array2.length);
var countMatched = 0,countNotMatched = 0;
for(var index=0;index<length;index++)
{
if(array1[index] == array2[index])
countMatched++;
else if(array2.indexOf(array1[index]) >= 0)
countNotMatched++;
}
alert(countMatched );
alert(countNotMatched);
Demo Fiddle : http://jsfiddle.net/tCKE7/2/
There is a JS library UnderscoreJS which provides a number of useful method for processing JavaScript arrays. You can use its difference method:
_.difference(['a','b','c','d'], ['a','d','c','e']) // returns ["b"]
If I interpret correctly, you want to find a count of elements that are at the same, exact position and a count of elements that are present in both arrays but not at the same position.
var array1 = ['a', 'b', 'c', 'd'];
var array2 = ['a', 'd', 'c', 'e'];
var largerArray = (array1.length > array2.length)? array1 : array2;
var shorterArray = (largerArray == array1)? array2 : array1;
var count = {
exactPosition: 0, //elements at the exact position
wrongPosition: 0 /*elements present in both arrays but at the wrong position*/
};
//loop the larger array
for(var i = 0; i < largerArray.length; i ++) {
if(array1[i] == array2[i]) {
count.exactPosition ++;
}
//find elements at the wrong position in `largerArray`
else if(largerArray.indexOf(shorterArray[i]) != -1) {
count.wrongPosition ++;
}
}
alert(count.exactPosition);
alert(count.wrongPosition);
This isn't a rock-solid approach and would not work for duplicates.
Array.indexOf
Fiddle: Fiddle