Reputation: 3414
I'm attempting to use JS to check a string for the most amount of the letters and append that result to a div. It looks so far like this:
var string = "AABBCCDDEEEEEEEEEE";
var stringInput = document.getElementById("string");
function showMostChar() {
var newInput = string.split("");
var inputAsArray = Array.of(newInput);
for (i = 0; i > inputAsArray; i++) {
if ((inputAsArray.indexOf("E")) > 9 ) {
stringInput.innerHTML = "E";
}
}
}
window.onload = showMostChar;
<div id="string"></div>
In plain english, I'm looking to split a string by character, which I then use to create an array. I loop through the array and if E has more than 9 (an arbitrary value) put E into the div. before I was using array()
but I remembered thats not a valid function, so I did research and found Array.of()
but I'm not seeing anything appended to string div.
is Array.of()
not the right way to create an array in this context? If not why?
The ideal scenario is to log the total amount of characters that appear the most, so in this instance EEEEEEEEEE
. I need to somehow get the value of each character and compare it to each other, somehow...something like:
for (i = 0; i > inputAsArray; i++) {
// somehow compare values to each other? e being each instance
// so, would that be a loop within a loop?
if ((i.value()) > e ) {
stringInput.innerHTML = i;
}
}
Upvotes: 1
Views: 72
Reputation: 32145
There are few things that needs to be fixed in your code:
.split()
will return an array
so newInput
is
already an array
, you don't need any transform it.array
is
Array.from()
, because Array.of()
takes a Number
as
argument..indexOf()
, you can directly call it upon newInput
array..indexOf()
will return
the first index
of E
in the array, which is lower than 9
, I
used 5
for testing purpose here.This is how should be your code:
function showMostChar() {
var newInput = string.split("");
if ((newInput.indexOf("E")) > 5 ) {
stringInput.innerHTML = "E";
}
}
Demo:
var string = "AABBCCDDEEEEEEEEEE";
var stringInput = document.getElementById("string");
function showMostChar() {
var newInput = string.split("");
console.log(newInput);
if ((newInput.indexOf("E")) > 5) {
stringInput.innerHTML = "E";
}
}
window.onload = showMostChar;
<div id="string"></div>
Edit:
To get the number of occurrences of E
in the array, you can use Array.filter()
like this:
function getNumberOfOccurences(char) {
var newInput = string.split("");
return newInput.filter(function(c){
return c === char;
}).length;
}
console.log(getNumberOfOccurences("E"));
Demo:
var string = "AABBCCDDEEEEEEEEEE";
var stringInput = document.getElementById("string");
function getNumberOfOccurences(char) {
var newInput = string.split("");
return newInput.filter(function(c){
return c === char;
}).length;
}
console.log(getNumberOfOccurences("E"));
Upvotes: 3