JavaScript: Number of given string in array - javascript

Not sure how to explain this in words, but is there any function in javascript that, when given a string , will return the number of times it occurs in an array?
For example:
var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.count("c");
With repeats then being equal to 3 as "c" occurs 3 times.
I tried to look this up but I wasn't sure on how to word it so I didn't get anything useful.

You can create your own function or add it to the prototype of Array:
Array.prototype.count = function (val){
var result = 0;
for(var i = 0; i < this.length; i++){
if(this[i] === val) result++;
}
return result;
}
Then you can do ['a','b', 'a'].count('a') // returns 2

You can use array.filter()
var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.filter(function(value) { return value==="c"; } ).length;
console.log(repeats)

arr.filter(function(v){return v=='c';}).length

Exact Word Match Example
var search_word = 'me';
var arr = ['help','me','please'];
arr.filter(function(el){return el === search_word}).length;
The filter function will return the element if the result of the function is true. The function is called on each element of the array. In this case, we are comparing the array element to our search word. If they are equal (true) the element is returned. We end up with an array of all the matches. Using .length simply gives us the number of items in the resulting array; effectively, a count.
Partial Match Example
If you were to want something a little more robust, for instance count the number of words that contain the letter l, then you could tokenize the string and scan the index, or use some regex which is a little more costly, but also more robust:
var search_word = 'l';
var arr = ['help','me','please'];
arr.filter( function(el){ return ( el.match(search_word) || [] ).length }).length;
Note that match also returns an array of matching elements, but an unsuccessful match returns undefined and not an empty array, which would be preferred. We need an array to use .length (the inside one), otherwise it would result in an error, so we add in the || [] to satisfy the case when no matches are found.

Related

Trouble understanding .indexOf in this code problem

I recently completed this Leetcode assessment for an open-book interview. Luckily I was able to Google for help, and passed the assessment. I'm having trouble understanding what exactly is happening on the line declared below. I'd love it if one of your smartypants could help me understand it better!
Thank you!
The problem:
Have the function NonrepeatingCharacter(str) take the str parameter being passed, which will contain only alphabetic characters and spaces, and return the first non-repeating character. For example: if str is "agettkgaeee" then your program should return k. The string will always contain at least one character and there will always be at least one non-repeating character.
Once your function is working, take the final output string and combine it with your ChallengeToken, both in reverse order and separated by a colon.
Your ChallengeToken: iuhocl0dab7
function SearchingChallenge(str) {
// global token variable
let token = "iuhocl0dab7"
// turn str into array with .split()
let arrayToken = token.split('')
// reverse token
let reverseArrayToken = arrayToken.reverse();
// loop over str
for (var i = 0; i < str.length; i++) {
// c returns each letter of the string we pass through
let c = str.charAt(i);
***--------------WHAT IS THIS LINE DOING?-------------***
if (str.indexOf(c) == i && str.indexOf(c, i + 1) == -1) {
// create variable, setting it to array with first repeating character in it
let arrayChar = c.split()
// push colon to array
arrayChar.push(':')
// push reversed token to array
arrayChar.push(reverseArrayToken)
// flatten array with .flat() as the nested array is only one level deep
let flattenedArray = arrayChar.flat()
// turns elements of array back to string
let joinedArray = flattenedArray.join('')
return joinedArray;
}
}
};
What I'd do is:
Reduce the string to an object, where the keys are the letters and the values are objects containing counts of occurrences and initial index in the string
Sort the .values() of that object in order of minimum count and minimum index
Use the first entry in the result of the sort to return the character
So something like
function firstUnique(str) {
const counts = Array.from(str).reduce((acc, c, i) => {
(acc[c] || (acc[c] = { c, count: 0, index: i })).count++;
return acc;
}, {});
return Object.values(counts).sort((c1, c2) =>
c1.count - c2.count || c1.index - c2.index
)[0].c;
}

Checking if an array contains exactly a specific set of integers

Is that possible to check if the variable array contains exactly the numbers 1,0,0,1?
For example,
var array = [1,0,0,1];
if (array === 1001) alert("success");
You can just join the array to check
The join() method joins all elements of an array (or an array-like
object) into a string and returns this string.
Note: You need to use == instead of === because join will return a string.
Like:
var array = [1, 0, 0, 1];
if ( array.join("") == 1001 ) alert("success");
As per suggestion below, you can also use === and compare it with a string.
var array = [1, 0, 0, 1];
if ( array.join("") === "1001" ) alert("success");
Please check more info about join: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Use the join() method to joins all elements of the array into a string and returns this string.
var elements = [1,0,0,1];
console.log(elements.join('') === "1001");
// expected output: true
Using the method join("") you conver your array into a string with out the commas
Then you use the includes("1001") to check for the expected result
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
var array = [1,0,0,1];
var string = array.join("");
console.log(string);
if (string.includes('1001')) alert("success");
Well, everyone gave a strict answer to your question; but I figured I would add on to it a little. Assuming you want this to be a little more dynamic. This way we check subsets of the array for the string you are looking for, rather than just the entire array.
Array.prototype.containsSequence = function(str, delimiter){
//Determines what is seperating your nums
delimiter = delimiter || '';
//Check the sub array by splicing it, then joining it
var checkSection = function (arr, start, end, str){
return arr.slice(start, end).join(delimiter) === str;
};
let start = 0; //start of our sub array
let end = str.length; //the length of the sub array
//Loop through each x size of sub arrays
while(end < this.length){
//Check the section, if it is true it contains the string
if(checkSection(this, start, end, str)){
return true;
}
//Incriment both start and end by 1
start++;
end++;
}
//We dont contain the values
return false;
};
///Test stuff
const ARRAY = [1,2,3,4,5,6,7,8,9,10];
if(ARRAY.containsSequence('456')){
console.log('It contains the str');
}else console.log('It does not contain');

Finding word in javascript

I have an sorted array e.g
var arr = [ "aasd","march","mazz" ,"xav" ];
And i want to find the first occurance of letter that starts with "m" here it would be 1 . Is thee any way how to do it without looping trought whole array?
You could use a binary search to find any word starting with that letter, then loop backwards until you get the first one.
Is there any way how to do it without looping trought whole array?
Yes, loop until you've found the match.
If you want to avoid a for or while construct, you can use Array's find() method.
For example, arr.find(word => word.startsWith("m")) should return the result you expect (or undefined if there's no such word).
You could use the find() function to search for the first match that meets your constraint.
The startsWith() function could easily handle this :
// Your array
var arr = [ "aasd","march","mazz" ,"xav" ];
// This will find the first match that starts with "m"
arr.find(function(word){ return word.startsWith('m');}); // yields "march"
Or if you needed a bit more extensive pattern matching, you could use a regular expression via the test() function, which can be seen in the following example and handles the same scenario (matching a string that begins with "m") :
// Your array
var arr = [ "aasd","march","mazz" ,"xav" ];
// First match that starts with "m"
var match = arr.find(function(word){ return /^m/i.test(word);}); // yields "march"
Example
var arr = ["aasd", "march", "mazz", "xav"];
var match = arr.find(function(word) { return /^m/i.test(word); });
alert(match);
You dont need to loop through the whole array - only until such time as you find what you're interested in
function findFirstIndex(arr, char){
for(var i=0;i<arr.length;i++){
if(arr[i].substring(0,1) === char)
return i;
}
return -1; // not found
}
You could use Array#some()
The some() method tests whether some element in the array passes the test implemented by the provided function.
function find(letter, array) {
var index;
array.some(function (a, i) {
if (a[0] === letter) {
index = i;
return true;
}
});
return index;
}
var arr = ["aasd", "march", "mazz", "xav"];
document.write(find('m', arr));

Javascript problems when converting a string to an array and then back again

I am trying to solve a Javascript challenge on Codewars.
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
isIsogram( "Dermatoglyphics" ) == true
isIsogram( "aba" ) == false
isIsogram( "moOse" ) == false // -- ignore letter case
My effort is below:
function isIsogram(str) {
var arr = str.split("");
var seen = {};
var out = [];
var length = arr.length;
var j = 0;
for(var i = 0; i < length; i++) {
var item = arr[i].toLowerCase;
if(seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
console.log(out.toString.toLowerCase);
console.log(str.toLowerCase);
if (out.toString.toLowercase === str.toLowerCase) {
return true;
}
else {
return false;
}
}
In codewars the result of my
console.log(out.toString.toLowerCase); is undefined
and the result of
console.log(str.toLowerCase); is [Function: toLowerCase].
This means my solution always evaluates to false.
I would appreciate any help to point me in the right direction or highlight my errors instead of giving me the solution so I can learn more effectively. Thanks!
This may be a simpler answer.
function isIsogram(str){
// Turn all letters of the string to lower case and split it into an array.
var letters = str.toLowerCase().split('');
var checkLetters = [];
/* Check to see if the letter appears in the checkLetters array.
If the letter is not already in the array it will push the letter into it. */
letters.forEach(function(letter) {
if(checkLetters.indexOf(letter) === -1) {
checkLetters.push(letter);
}
});
/* Now we have two arrays. If the letters array has non-duplicate letters then
it will be the same length as the checkLetters array. If not, the checkLetters array
will be shorter. */
/* Return true or false depending on whether the lengths of both arrays are equal */
return letters.length === checkLetters.length ? true : false;
}
toString and toLowerCase are functions. In Javascript, to execute a function, you must add parenthesis on to the end of the function name:
out.toString().toLowerCase()
// ^^ ^^
You need to do this for all your functions:
arr[i].toLowerCase()
str.toLowerCase
out.toString.toLowercase() === str.toLowerCase()
(Note that calling .toString() on an array will include commas, e.g. "a,b,c,d,e". Probably doesn't matter for this use case, but just to highlight that)
toString and toLowerCase etc are functions
use:
out.toString().toLowerCase()
however, for out, I think you want to do out.join('').toLowerCase()
I think that you can improve your solution, by doing in the functional way, using hashmap system, and every method.
The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value
So, your code will be more clean.
function isIsogram(str) {
//Create our hashmap
var hashmap = {};
//Return value of 'every' loop
return str.split("").every(function(elm){
//If our hashmap get current letter as key
return hashmap.hasOwnProperty(elm.toLowerCase())
//Return false, str is not an Isogram
? false
//Otherwise, set letter as key in our hashmap,
//we can check the next iteration
: hashmap[elm.toLowerCase()] = true;
});
}
console.log(isIsogram('Dermatoglyphics'));
console.log(isIsogram('moOse'));
console.log(isIsogram('aba'));
I know you've solved this, but just for variety.
By ignoring case sensitivity, first change the input to lowercase.
function isIsogram(str) {
// Change word to lower case
str = str.toLowerCase();
// split the word into letters and store as an array
var arr = str.split("");
// get the length so the array can be looped through
var len = arr.length;
// an array to contain letters that has been visited
var seen = []
for (var i = 0; i < len; i++) {
// check if letter has not been visited by checking for the index
if(seen.indexOf(arr[i])<0){
// if the letter doesn't exist,add it to seen and go to next letter
seen.push(arr[i]);
}else{
// if letter exists, the word is not an isogram return false
return false
}
}
// the loop is complete but each letter appeared once, the word is an isogram
return true
}
console.log(isIsogram('Dermatoglyphics'));
console.log(isIsogram('moOse'));
console.log(isIsogram('aba'));

Javascript check every char in a string and return array element on corresponding position

Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i

Categories