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');
Related
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;
}
I need some help. I need to match some value with one variable containing value which is comma separated string using Angular.js or Javascript. I am explaining my code below.
var special="2,1,4,5";
Here I need to search lets say 1 is present in this comma separated string or not. If the given value is present it will return true otherwise false.Please help.
With array split
var found = special.split(",").indexOf("1") > -1;
var special="2,1,4,5";
var found = special.split(",").indexOf("1") > -1;
console.log(found); // true
Just to prove that String's indexOf won't work
var special="2,11,4,5";
var found = special.indexOf("1") > -1;
console.log(found); // true but actual should be false as there is no 1
Try this,
var special="2,1,4,5";
var searchFor="1";
var index=special.split(",").indexOf(searchFor);
if(index === -1) return false;
else return true;
You can first convert the string to an array like this:
var specialArray = special.split(',');
Once you have an array you can use indexOf to find the item in the array.
var itemIndex = specialArray.indexOf('1');
itemIndex will be -1 when the value you're looking for isn't in the array. When the result of indexOf is greater than -1 it is the index of the item in the array.
You can use regular expression for this:
/(^|,)1(,|$)/.test("2,1,4,5") // => true
just to test negative case
/(^|,)1(,|$)/.test("2,11,4,5") // => false
If you have multiline string (that contains \r\n), use /(^|,)1(,|$)/m instead
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.
I will start this question with the statement that I'm really bad with regex.
Said this, I wonder if possible to filter an array using jquery $.grep, match strings with an specific string, something like this:
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var s = a.split(",");
var array = $.grep(s, function(x, y) {
return ??????;
});
so after applying $.grep or any other function which could help, i will need the after ":" number of those with ABC, so my new array would be:
array[12, 2];
Any help with this??? I would really appreciate!
$.grep only select elements of an array which satisfy a filter function.
You need additional step to $.map all numbers from grepped array.
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var b = $.grep(a, function(item) {
return item.indexOf("ABC:") >= 0;
});
var array = $.map(b, function(item) {
return item.split(":").pop();
});
Try
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
// map array ,
// test array items for "ABC" string ,
// filter `Number` in strings containing "ABC" ,
// return filtered Numbers , in newly mapped array
var s = $.map(a, function(n) {
return (/ABC/.test(n) ? Number(n.split(":").filter(Number)) : null)
}); // [12, 2]
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