I have following function:
var sortString = function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return 1;
if (a > b) return -1;
return 0;
}
and I have following two strings:
x = ["B1C3N_EUR_DFAK_ALL_3M_ALL","B1C3N_EUR_BPP_BCO_3M"];
When I run the above function on this array. I expect "B1C3N_EUR_BPP_BCO_3M" to be at index 0 whereas browser returns it in the reverse order. I have checked both on Chrome and IE. Why is it so??
Do I need to replace "-" with some other values. Is there any way I can do it without replacing.
You return the wrong value for smaller and greater value in the callback for Array#sort.
if (a < b) return 1;
// ^ should be -1, because a is smaller than b
if (a > b) return -1;
// ^^ should be 1, because a is greater than b
For a more concise style, you could use String#localeCompare, which test the given strings and returns a value in the wanted range.
Related
Write a function that takes three (str, c, n) arguments. Start with the end of 'str'. Insert character c after every n characters?
function three(str, c, n){
for(let i =0; i<str.length; i= i+n){
str.slice(i, i+n);
str = str + c;
}
return str;
}
console.log(three("apple", "c", 2));
I think, I am using wrong method.
Start with the end of 'str'. Insert character c after every n characters?
I assumed this means the string needs to end with c after the change. Correct me if I'm wrong.
If that's the case Array.prototype.reverse() and Array.prototype.map() can help here:
function three (str, c, n) {
return str.split('').reverse().map((currentValue, currentIndex, array) => {
if (currentIndex % n === 0) {
return currentValue + c
} else {
return currentValue
}
}).reverse().join('')
}
console.log(three("apple", "c", 2));
You can do something like that :
function three(str, c, n){
// split the string into an array
let letters = str.split('');
// copy to another array that will be the end result to avoid modifying original array
let result = [...letters];
// When we add to the array, it shift the next one and so on, so we need to account for that
let shift = 0;
// we go over each letter
letters.forEach((letter,index) => {
// if we are at the desired location
if(index > 0 && index % n == 0) {
// we add our letter at that location
result.splice(index+shift, 0, c);
// we increase shift by 1
shift++;
}
})
// we return the result by joining the array to obtain a string
return result.join('');
}
console.log(three("apple", "c", 2));//apcplce
Here, it does not work because the Array#slice does not update the actual string but returns a new string.
returns a shallow copy of a portion of an array into a new array object selected from start to end
In my opinion, the easiest way to solve your problem here would be to split the word into characters using the Array#split method, the add the char to each item if the index match the n parameters and finally, re-join the array
function three(str, c, n){
const strAsChar = str.split('')
return strAsChar.map((char, index) => (index - 1) % n === 0 ?
char + c :
char
).join('')
}
console.log(three("apple", "c", 2));
I'm trying to write a function (GetPositiveInteger) that generates a random integer between variables a and b. if a > b, it's supposed to switch the values of the two so that b=>a before generating the Number.
I don't know if I'm misunderstanding the question or what because I can't figure out where I'm meant to be converting a and b to integers and my program keeps just returning NaN. here's my code maybe someone could take a look at it?
function GetRandomInteger(a, b, c) {
a = Number(a), b = Number(b);
if (a > b) {
var a = 2,
b = 1,
c = a;
a = b;
b = c;
} else {
var x = parseInt(Math.random() * b) + a;
}
return x;
}
let x;
console.log(Number(GetRandomInteger(x)));
When a > b, you're setting them to specific numbers before swapping them, instead of swapping the original values.
The code that generates the random number shouldn't be in else, because you won't run that after swapping a and b. It should just be after the if.
You don't need the c parameter. Use a temporary variable declared inside the function when swapping.
Use Math.floor() to convert a floating point number to an integer. parseInt() is for parsing strings (it will work in this case because it first converts the float to a string, but it's better to use the more specific function).
You need to call the function with two arguments. In the example below I just hard-coded them, but you can use your function that asks the user for numbers. Just use it twice to set two variables.
function GetRandomInteger(a, b) {
a = Number(a), b = Number(b);
if (a > b) {
let temp = a;
a = b;
b = temp;
}
var x = Math.floor(Math.random() * b) + a;
return x;
}
console.log(GetRandomInteger(1, 10));
console.log(GetRandomInteger(15, 3));
I have series of numbers as strings I want to sort.
for example
4604158/1/7,4604181/1/2,4604158/1/8,4604182/1/2,4604181/1/3, 4604282/1/2 etc.
how can I achieve this with knockout js or even with simple javascript?
I am able to sort only numbers (without slashes) with the following code :
myObservableArray.sort(function (item1, piece2) {
return item1.stringWithSlashes < item2.stringWithSlashes ? -1 : (item1.stringWithSlashes > item2.stringWithSlashes ? 1 : 0);
});
You could split the strings and sort then with the first part, then the second and if equal by the third part.
var array = ['4604158/1/7', '4604181/1/2', '4604158/1/8', '4604182/1/2', '4604181/1/3', '4604282/1/2'];
array.sort(function (a, b) {
var aa = a.split('/'),
bb = b.split('/');
return aa[0] - bb[0] || aa[1] - bb[1] || aa[2] - bb[2];
});
console.log(array);
This is a dynamic way to check with any separator and any length of separated result array.
var array = ['4604158/1/7', '4604181/1/2', '4604158/1/8', '4604182/1/2', '4604181/1/3', '4604282/1/2'];
var separator = '/';
array.sort(function(a, b) {
b = b.split(separator);
return a.split(separator)
.some((v, i) => (+v > +b[i]));
})
console.log(array);
I have this sorting function, but which i use to sort a table, i can sort by dates (which i have removed for simplicity) and strings, but intergers are acting wierd, a common case is that all values could be 0, which will give the array
[0,0,0,0]
this works perfectly in firefox but not in chrome, it changes the order of the rows in my table although they are equal, i have even followed the ECMA standards. Why do chrome change the order anyway? I have also tried using
return (ascending_order ? a - b : b - a)
But with the same result as my more general approach to work with different data types
arr.sort(function(a, b){
var onlydigitsRegex = new RegExp("\d+","g");
if (a.match(onlydigitsRegex) && b.match(onlydigitsRegex)) {
a = parseInt(a);
b = parseInt(b);
} else {
a = a.toLowerCase();
b = b.toLowerCase();
}
return (a === b) ? 0 : (ascending_order ? ((a > b) ? 1 : -1) : ((a < b)? 1 : -1));
});
I need to sort an array based on Alphabets. I have tried sort() method of javascript, but it doesn't work since my array consists of numbers, lowercase letters and uppercase letters. Can anybody please help me out with this? Thanks
For e.g my array is:
[
"#Basil",
"#SuperAdmin",
"#Supreme",
"#Test10",
"#Test3",
"#Test4",
"#Test5",
"#Test6",
"#Test7",
"#Test8",
"#Test9",
"#a",
"#aadfg",
"#abc",
"#abc1",
"#abc2",
"#abc5",
"#abcd",
"#abin",
"#akrant",
"#ankur",
"#arsdarsd",
"#asdd",
"#ashaa",
"#aviral",
"#ayush.kansal",
"#chris",
"#dgji",
"#dheeraj",
"#dsfdsf",
"#dualworld",
"#errry",
"#george",
"#ggh",
"#gjhggjghj"
]
a.sort(function(a, b) {
var textA = a.toUpperCase();
var textB = b.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
This should work (jsFiddle)
function alphabetical(a, b){
var c = a.toLowerCase();
var d = b.toLowerCase();
if (c < d){
return -1;
}else if (c > d){
return 1;
}else{
return 0;
}
}
yourArray.sort(alphabetical);
To sort an array by a key function applied to an element (toUpperCase here), Schwartzian transform, aka "decorate-sort-undecorate" is your technique of choice:
cmp = function(x, y) { return x > y ? 1 : x < y ? -1 : 0 }
sorted = array.map(function(x) {
return [x.toUpperCase(), x]
}).sort(function(x, y) {
return cmp(x[0], y[0])
}).map(function(x) {
return x[1]
})
The major advantage of this approach is that the key function is called exactly once for each element, which can matter when the key is heavy or has side effects.
I realize that you're looking for a simple answer right now, but this might be something for you to consider learning in the future.