Python String.startswith() with a list of strings in Javascript - javascript

Python startswith() allows me to test if a string starts with a tuple of strings as shown below, which is what I want to achieve with JavaScript:
testvar = 'he', 'hi', 'no', 'ye'
if my_string.startswith(testvar):
return True
I have seen this SO question and it did not completely help in achieving this.
I need to have a JavaScript code that will do the same thing with the Python code above.

Since there has been many solutions for having an array passed as argument, I am gonna post a solution splat "*" style arguments:
String.prototype.startsWithSplat = function(){
var args = Array.prototype.slice.call(arguments, 0, arguments.length);
var i;
var matched = false;
var self = this;
for(i = 0; i < args.length; i++){
if(self.slice(0, args[i].length) == args[i]){
matched = true;
break;
}
}
return matched;
}
Then you can just call:
my_string.startswith('he', 'hi', 'no', 'ye');

All you need is a simple loop over an Array with one of the answers shown there,
var testvar = ['he', 'hi', 'no', 'ye'];
function startsWith2(haystack, needles) {
var i = needles.length;
while (i-- > 0)
if (haystack.lastIndexOf(needles[i], 0) === 0)
return true;
return false;
}
startsWith2('hello world', testvar); // true
startsWith2('foo bar baz', testvar); // false
Similarly for endsWith;
function endsWith2(haystack, needles) {
var i = needles.length, j, k = haystack.length;
while (i-- > 0) {
j = k - needles[i].length;
if (j >= 0 && haystack.indexOf(needles[i], j) === j)
return true;
}
return false;
}

Since they're all the same length you could just do:
testvar = ['he', 'hi', 'no', 'ye']
return testvar.indexOf(my_string.substring(0,2)) > -1
And some examples:
// Examples:
testvar = ['he', 'hi', 'no', 'ye']
my_string = 'hello'
testvar.indexOf(my_string.substring(0,2)) > -1
true
my_string = 'apples'
testvar.indexOf(my_string.substring(0,2)) > -1
false

You can run a reduce operation over your array of tests to find if a variable starts with any of them.
var testVar = ['he', 'hi', 'no', 'ye'];
var myString = 'hello';
var startsWithAny = testVar.reduce(function (returnValue, currentTest) {
return returnValue || myString.startsWith(currentTest);
});
if (startsWithAny) {
return true;
}

var testvar = ['he','hi','no','ye'];
var str = "hello";
for(i = 0; i < testvar.length; i++)
{
if (str.startsWith(testvar[i]) == true)
console.log(str+" starts with: "+testvar[i]);
}

Related

javascript check values are same or not within double quotes?

In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not
var str= "0,1,-1";
How to check this variable.
The author wants to compare these 3 values. You most separate this variable with split:
var str= "0,1,-1",
arr = str.split(',');
all are same or not ie, true are false compare this array with function every
var str= "0,1,-1",
arr = str.split(',');
var res = arr.every(function (item) {
return item == arr[0];
})
console.log(res);
Short solution using String.prototype.split() and Set object:
var hasSameValues = function (s) {
return (new Set(s.split(','))).size === 1;
};
console.log(hasSameValues("0,1,-1"));
console.log(hasSameValues("1,1,1"));
console.log(hasSameValues("2,-2,2"));
you can split and then check for every item in splitted array.
check the fiddle
code is below -
var val = "1, 01, 0001";
var result = function(val)
{
var l = val.length;
if(l == 0)
{
return false;
}
else
{
//because all the values in 'val' fields are number
var f = Number.parseInt(val[0]) ;
for(i=1; i< l; i++)
{
if(Number.parseInt(val[i]) != f)
{
return false;
}
}
return true;
}
}(val.split(','))
alert(result);

Checking if the characters in a string are all unique

I am trying to solve this problem using JS by just using an array.
var str = 'abcdefgh';
for (i = 0; i < 255; i++) {
arr[i] = false;
}
function check() {
for (i = 0; i < str.length; i++) {
if (arr[str.charCodeAt(i)] == true) {
return false;
}
arr[str.charCodeAt(i)] = true;
}
return true;
}
I am initializing an array of fixed size 256 to have the boolean value false.
Then i am setting the value for the corresponding ASCII index to true for characters in the string. And if i find the same character again, i am returning false.
While running the program, i am getting false returned even if the string doesn't have any duplicate characters.
Fill a Set with all characters and compare its size to the string's length:
function isUnique(str) {
return new Set(str).size == str.length;
}
console.log(isUnique('abc')); // true
console.log(isUnique('abcabc')); // false
Use object for faster result
function is_unique(str) {
var obj = {};
for (var z = 0; z < str.length; ++z) {
var ch = str[z];
if (obj[ch]) return false;
obj[ch] = true;
}
return true;
}
console.log(is_unique("abcdefgh")); // true
console.log(is_unique("aa")); // false
use .match() function for each of the character. calculate occurrences using length. Guess thats it.
(str.match(/yourChar/g) || []).length
We can also try using indexOf and lastIndexOf method:
function stringIsUnique(input) {
for (i = 0; i < input.length; i++) {
if (input.indexOf(input[i]) !== input.lastIndexOf(input[i])) {
return false;
}
}
return true;
}
You are using arr[str.charCodeAt(i)] which is wrong.
It should be arr[str[i].charCodeAt(0)]
var arr = [];
var str="abcdefgh";
for (i=0;i<255;i++){
arr[i]=false;
}
function check(){
for (i=0;i<str.length;i++){
if (arr[str[i].charCodeAt(0)]==true){
return false;
}
arr[str[i].charCodeAt(0)]=true;
}
console.log(arr);
return true;
}
check();
Time complexity = O(n)
Space complexity = O(n)
const isUnique = (str) => {
let charCount = {};
for(let i = 0; i < str.length; i++) {
if(charCount[str[i]]){
return false;
}
charCount[str[i]] = true;
}
return true;
}
const isUniqueCheekyVersion = (str) => {
return new Set(str).size === str.length;
}
Solution 3:
Transform string to chars array, sort them and then loop through them to check the adjacent elements, if there is a match return false else true
Solution 4:
It's similar to Solution 1 except that we use a Set data structure which is introduced in recent versions of javascript
// no additional Data structure is required. we can use naive solution
// Time Complexity:O(n^2)
function isUnique(str) {
for (let i = 0; i < str.length; i++) {
for (let j = 1 + i; j < str.length; j++) {
if (str[i] === str[j]) {
return false;
}
}
}
return true;
}
// if you can use additional Data structure
// Time Complexity:O(n)
function isUniqueSecondMethos(str) {
let dup_str = new Set();
for (let i = 0; i < str.length; i++) {
if (dup_str.has(str[i])) {
return false;
}
dup_str.add(str[i]);
}
return true;
}
console.log(isUniqueSecondMethos('hello'));
Use an object as a mapper
function uniqueCharacterString(inputString) {
const characterMap = {};
let areCharactersUnique = true;
inputString.trim().split("").map((ch)=>{
if(characterMap[ch]===undefined) {
characterMap[ch] = 1;
} else {
areCharactersUnique = false;
}
})
return areCharactersUnique;
}
Algo
*1. step -first string is ->stack *
*2.step-string covert to CharArray *
3. step - use iteration in array ['s','t','a','c','k']
4. step - if(beginElement !== nextElement){return true}else{return false}
Implement code
function uniqueChars(string){
var charArray = Array.from(string) //convert charArray
for(var i=0;i<charArray.length;i++){
if(charArray[i] !== charArray[i+1]){
return true
}
else{
return false
}
}
}
var string ="stack"
console.log(uniqueChars(string))
Time complexity
O(nlogn)
Algo
Counting frequency of alphabets. e.g. 'Mozilla' will returns Object{ M: 1, o: 1, z: 1, i: 1, l: 2, a: 1 }. Note that, the bitwise NOT operator (~) on -~undefined is 1, -~1 is 2, -~2 is 3 etc.
Return true when all occurrences appear only once.
Implement code
var isUnique = (str) => {
const hash = {};
for (const key of str) {
hash[key] = -~hash[key];
}
return Object.values(hash).every((t) => t === 1);
};
console.log(isUnique('Mozilla'));
console.log(isUnique('Firefox'));
Another alternative could be:
var isUnique = (str) => {
const hash = {};
for (const i in str) {
if (hash[str[i]]) return false;
hash[str[i]] = true;
}
return true;
};
console.log(isUnique('Mozilla'));
console.log(isUnique('Firefox'));
To make efficient one, you can use simple hash map
let isUnique = (s) => {
let ar = [...s];
let check = {};
for (let a of ar) {
if (!check[a]) {
check[a] = 1;
} else {
return false
}
}
return true;
}
alert("isUnique : "+isUnique("kailu"));
Time complexity & Space complexity
using ES6
let isUnique = (s)=>{
return new Set([...s]).size == s.length;
}
console.log("using ES6 : ",isUnique("kailu"));
We can use split method of string:
const checkString = (str) => {
let isUniq = true;
for (let i = 0; i < str.length; i++) {
if (str.split(str[i]).length > 2) {
isUniq = false;
break;
}
}
return isUniq;
};
console.log(checkString("abcdefgh")); //true
console.log(checkString("aa")); //false

array.contains(array) in JavaScript

Is there an easy way of knowing if and array contains all elements of another array?
Example:
var myarray = [1,2,3];
var searchinarray = [1,2,3,4,5];
searchinarray contains all elements of myarray, so this should return true.
Regards
Here is an implementation of that function:
function contains(a, s) {
for(var i = 0, l = s.length; i < l; i++) {
if(!~a.indexOf(s[i])) {
return false;
}
}
return true;
}
This shows that it does what you describe:
> var myarray = [1,2,3];
> var searchinarray = [1,2,3,4,5];
> contains(myarray, searchinarray)
false
> contains(myarray, [1,2])
true
> contains(myarray, [2,3])
true
A contains function should only visit members of the array to be contained that exist, e.g.
var myArray = [1,,2];
var searchInArray = [1,2,3];
contains(myArray, searchInArray);
should return true, however a simple looping solution will return false as myArray[1] doesn't exist so will return undefined, which is not present in the searchInArray. To easily avoid that and not use a hasOwnProperty test, you can use the Array every method:
function contains(searchIn, array) {
return array.every(function(v){return this.indexOf(v) != -1}, searchIn);
}
so that:
var a = [1,,3];
var s = [1,2,3,4,5];
console.log(contains(s, a)); // true
You can add a contains method to all instances of Array if you wish:
if (typeof Array.prototype.contains == 'undefined') {
Array.prototype.contains = function(a) {
return a.every(function(v, i) {
return this.indexOf(v) != -1;
}, this);
}
}
console.log(s.contains(a)); // true
console.log(s.contains([1,9])); // false
You may need a polyfill for browsers that don't have .every (IE 8?).
function compare(array, contains_array) {
for(var i = 0; i < array.length; i++) {
if(contains_array.indexOf(array[i]) == -1) return false;
}
return true;
}
compare(myarray, searchinarray);

Multidimensional Array - Test if all values are equivilant in nested array

So, I have an array that looks like this:
[ ["","",""], ["","",""], ["","",""] ]
How would I test it in javascript to see if, perhaps, the 1st index was filled with X's?
EX: [ ["X","X","X"], ["","",""], ["","",""] ]
I keep thinking I should do something like this, but it feels like there would be a quicker way...
var counter = 0,
win,
b = [ ["X","X","X"], ["","",""], ["","",""] ],
num = b[0].length;
for(var i=0; i<num; i++){
if(b[0][i]==="X"){ counter++; }
}
if(num===counter){ win=true; }
var win = b[0].join('') === 'XXX';
Use Array.prototype.every. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
function isAnX(c) { return c === 'X'; }
var win = b[0].every(isAnX);
win = true;
for (var i = 0; i < num; i++) {
if (b[0][i] != "X") {
win = false;
break;
}
}
Here's how to test if an array contains identical elements:
allTheSame = someArray.every(function(x, _, ary) { return x == ary[0] })
see every
or, for pre-ES5 engines:
allTheSame = function(ary) {
for(var i = 1; i < ary.length; i++)
if(ary[i] != ary[0]) return false;
return true;
}
use Array.prototype.reduce
var win=b[0].reduce(function (v, c) { return v && (c=="X") }, true);
Another one, just to give one more option:
var win = new RegExp("^X{"+b[0].length+"}$").test(b[0].join(''));
Cheers
Similar to other answers, but with something of a twist:
var all = function(val, arr) {
var fn = function(arr) {return arr.every(function(item) {return item === val;});};
return arguments.length > 1 ? fn(arr) : fn;
};
var win = all('X', b[0]); //=> true
// or
var allXs = all('X');
var win = allXs(b[0]); //=> true
Or if you just want to know if they're all the same:
var allAlike = function(arr) {
return (arr.length == 0) || all(arr[0], arr);
}
var win = allAlike(b[0]);
This would be easier if you had an appropriate curry-like function available.
Hahaha, this is cool:
var win = Array(b[0].length+1).join('X') == b[0].join('')
Cheers!

indexOf( object) in javascript [duplicate]

This question already has answers here:
indexOf method in an object array?
(29 answers)
Closed 9 years ago.
Error in following code:-
var x = [{id: 'abc'}, {id: 'xyz'}];
var index = x.indexOf({id: 'abc'});
What's the syntax for above?
You should pass reference to exactly the same object you have defined in the array:
var a = {id: 'abc'},
b = {id: 'xyz'};
var index = [a, b].indexOf(a); // 0
Objects are only equal to each other if they refer to the exact same instance of the object.
You would need to implement your own search feature. For example:
Array.prototype.indexOfObject = function(obj) {
var l = this.length, i, k, ok;
for( i=0; i<l; i++) {
ok = true;
for( k in obj) if( obj.hasOwnProperty(k)) {
if( this[i][k] !== obj[k]) {
ok = false;
break;
}
}
if( ok) return i;
}
return -1; // no match
};
var x = [{id: 'abc'}, {id: 'xyz'}];
var index = x.indexOfObject({id: 'abc'}); // 0
Iterate through the array like this:
for(var i = 0, len = x.length; i < len; i++) {
if (x[i].id === 'abc') {
console.log(i);
break;
}
}
Otherwise, you'll have to make sure the pointers are the same for the objects you're trying to look for with indexOf
Let's have some nice code here ;)
Underscore.js provides where, which is also fairly easy to write in pure JS:
Array.prototype.where = function(props) {
return this.filter(function(e) {
for (var p in props)
if (e[p] !== props[p])
return false;
return true;
});
}
Another (more flexible) function understands either an object or a function as a selector:
Array.prototype.indexBy = function(selector) {
var fn = typeof selector == "function" ? selector :
function(elem) {
return Object.keys(selector).every(function(k) {
return elem[k] === selector[k]
})
}
return this.map(fn).indexOf(true);
}
and then
var x = [{id: 'abc'}, {id: 'xyz'}];
x.indexBy({'id': 'xyz'}) // works
x.indexBy(function(elem) { return elem.id == 'xyz' }) // works too
var o = {}
var x = [o]
console.log(x.indexOf(o))
With x.indexOf({}) you create a new Object the is not present in the array
The following is the most wonderful method:-
var indexId = x.map(function(e) { return e.id; }).indexOf('abc');
as seen in this answer

Categories

Resources