How to use regex on string within a switch statement? - javascript

I have an if else statement to match a string with vowels and consonants which works fine. I would like to tidy it up with a switch statement however using match() does not work as a case. what am i missing?
if else //returns vowels: 1, consonants: 3
function getCount(words) {
var v,
c;
if (words === '' || words === ' ') {
v=0;
c=0;
} else if(words.match(/[aeiou]/gi)) {
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
} else {
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
getCount('test');
switch //returns vowels: 0, consonants: 0
function getCount(words) {
var v,
c;
switch(words) {
case words.match(/[aeiou]/gi):
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
console.log("true");
break;
case '':
case ' ':
v = 0;
c = 0;
break;
default:
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
getCount('test');

// Code goes here
function getCount(words) {
var v,
c;
switch(true) {
case ( words.match(/[aeiou]/gi) !=null ):
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
console.log("true");
break;
case (words==''):
case (words==' '):
v = 0;
c = 0;
break;
default:
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
console.log(getCount('test'));

Your switch statement needs to evaluate an expression and compare the result to the value of each case statement.
function getCount(words) {
var v,
c;
switch(words.match(/[aeiou]/gi).length > 0) {
case true:
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
console.log("true");
break;
default:
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
getCount('test');

Related

delete character of 2 string to make them anagram in typescript

I tried to solve one of the Hackerrank challenges String: Making Anagrams
I have 2 strings like this:
let a: string = "fcrxzwscanmligyxyvym"
let b: string = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"
and I have a function that only passed 3 tests!!! :
function makeAnagram(a: string, b: string): number {
type Map = {
[key :string] : number
}
let string1 = a.split('')
let string2 = b.split('')
let map : Map = {}
let deletedCount = 0
let firstCount = 0
let isMoreThanTwo = false
for(let i of string1) {
map[i] = (map[i] | 0) + 1
}
for(let i of string2){
map[i] = (map[i] | 0) + 1
}
for(let i in map) {
if(map[i] == 1) {
deletedCount++
firstCount++
} else if(map[i] > 2) {
isMoreThanTwo = true
deletedCount += (map[i] - 1)
}
}
return isMoreThanTwo ? deletedCount + firstCount : deletedCount
is there any other solution to count deleted characters? and can you guys give me some advice, thank you
I've just solved this problem but before passing all test cases I came to a solution where I used
for (let [k, v] of map) {
remain += v;
}
which failed 13/16 test cases, then I debugged the program and came to know that sometimes when we subtract 1 from the previous of this step, It goes less than 0 so Yo also have to handle this case, I handles as
for (let [k, v] of map) {
remain += v < 0 ? v * -1 : v;
}
Now, all test cases are passed
function makeAnagram(a, b) {
const [small, big] = a.length < b.length ? [a, b] : [b, a];
const map = new Map();
for (let c of small) {
map.set(c, (map.get(c) ?? 0) + 1);
}
let remain = 0;
for (let c of big) {
!map.has(c) ? remain++ : map.set(c, map.get(c) - 1);
}
for (let [k, v] of map) {
remain += v < 0 ? v * -1 : v;
}
return remain;
}
console.log(makeAnagram("fast", "sofasty"));

(JavaScript) Without using eval(), write a function that determines if the relation between two numbers written as a string is true

Examples:
isTrue("2=2") ➞ true
isTrue("8<7") ➞ false
isTrue("5=13") ➞ false
isTrue("15>4") ➞ true
Here is what I have so far ---
let test1 = '2=2';
let test2 = '8<7';
let test3 = '5=13';
let test4 = '15>4';
function isTrue(relation) {
let separate = [];
let num1 = 0;
let num2 = 0;
let newArray = [];
let a = 0;
let b = 0;
if (relation.includes('=')) {
separate = relation.split('=');
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
} else if (relation.includes('<')) {
separate = relation.split('<');
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
} else if (relation.includes('>')) {
separate = relation.split('>');
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
} else {
return 'This is not a valid comparison. Please try again.';
}
if (relation.includes('=')) {
a = newArray[0];
b = newArray[1];
if ((a = b) === true) {
return true;
} else {
return false;
}
} else if (relation.includes('<')) {
a = newArray[0];
b = newArray[1];
if ((a < b) === true) {
return true;
} else {
return false;
}
} else if (relation.includes('>')) {
a = newArray[0];
b = newArray[1];
if ((a > b) === true) {
return true;
} else {
return false;
}
} else {
return 'This is not a valid comparison. Please try again.';
}
}
console.log(isTrue(test1));
console.log(isTrue(test2));
console.log(isTrue(test3));
console.log(isTrue(test4));
I would especially appreciate help with solving this problem while still somewhat following the logic I've started using to solve it. What I really want to do is declare a variable that somehow holds an empty function, then update the empty function with a comparison function based on which comparison operator is present, but I don't think that's allowed in JavaScript. Right now all tests are returning false.
Thanks in advance!!
You could take the parts of the expression and an object for the operators.
Return the result of the call of the function of the operator with numerical values.
function isTrue(expression) {
const
operators = {
'=': (a, b) => a === b,
'<': (a, b) => a < b,
'>': (a, b) => a > b
},
[, a, operator, b] = expression.match(/^(\d+)(\D+)(\d+)$/);
return operators[operator]?.(+a, +b) || false;
}
console.log(isTrue("2=2")); // true
console.log(isTrue("8<7")); // false
console.log(isTrue("5=13")); // false
console.log(isTrue("15>4")); // true
console.log(isTrue("15#4")); // false
Approach for floats
function isTrue(expression) {
const
operators = {
'=': (a, b) => a === b,
'<': (a, b) => a < b,
'>': (a, b) => a > b
},
[a, operator, b] = expression.split(new RegExp('(' + Object
.keys(operators)
.join('|')
+ ')'));
return operators[operator]?.(+a, +b) || false;
}
console.log(isTrue("2.3=2.3")); // true
console.log(isTrue("8<7")); // false
console.log(isTrue("5=13")); // false
console.log(isTrue("4.2>4.1")); // true
console.log(isTrue("15#4")); // false
a = b is an assignation, not a comparison, so when you write (a = b) == true it's very strange and (a == b) == true will be better I mean. But know here is a form of your function, I prefer:
function isTrue(relation){
let separate = [];
let num1 = 0;
let num2 = 0;
let newArray = [];
let a = 0;
let b = 0;
if (relation.includes('=')) {
separate = relation.split('=');
} else if (relation.includes('<')) {
separate = relation.split('<');
} else if (relation.includes('>')) {
separate = relation.split('>');
} else {
return 'This is not a valid comparison. Please try again.';
}
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
a = newArray[0];
b = newArray[1];
if (relation.includes('=')) {
return a == b;
} else if (relation.includes('<')) {
return a < b;
} else {
return a > b;
}
}
console.log(isTrue("2=2")); // true
console.log(isTrue("8<7")); // false
console.log(isTrue("5=13")); // false
console.log(isTrue("15>4")); // true
console.log(isTrue("test")); // No valid comparison
You just need to return the boolean of your comparison Example return a == b. Here I simplified your code.
If you want to compare floats you just need to change parseInt by parseFloat and take attention to the numbers format.
Ok all I took a break and came back to it. Saw my error. Code is now working, see below:
let test1 = '2=2';
let test2 = '8<7';
let test3 = '5=13';
let test4 = '15>4';
function isTrue(relation) {
let separate = [];
let num1 = 0;
let num2 = 0;
let newArray = [];
let a = 0;
let b = 0;
if (relation.includes('=')) {
separate = relation.split('=');
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
a = newArray[0];
b = newArray[1];
if (a === b) {
return true;
} else {
return false;
}
} else if (relation.includes('<')) {
separate = relation.split('<');
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
a = newArray[0];
b = newArray[1];
if (a < b) {
return true;
} else {
return false;
}
} else if (relation.includes('>')) {
separate = relation.split('>');
num1 = parseInt(separate[0]);
num2 = parseInt(separate[1]);
newArray = [num1, num2];
a = newArray[0];
b = newArray[1];
if (a > b) {
return true;
} else {
return false;
}
} else {
return 'This is not a valid comparison. Please try again.';
}
}
isTrue(test1);
isTrue(test2);
isTrue(test3);
isTrue(test4);

How to change all AJAX requests to add token header from cookies

I need to send all my XHR requests with a header named token and value coming from cookies.
I found a solution, but the code is very very long - and a bit ugly (insert a full external library - so big - just to use a simple function...)
The need to use swagger-ui. I get the token from ADFS by clicking on Authorize btn. But for all the others request (test performed using try it out btn)
Because I was not able to find a solution with the Swagger configuration, I decide to use a workaround: Change all the AJAX request on the fly.
I already tried to do it using Jquery or direct Javascript codes, but none of them were working.
Finally, I find a solution using XHook (v1.4.9 - https://github.com/jpillora/xhook)
Here is the code of my file (injected into the index page)
// XHook - v1.4.9 - https://github.com/jpillora/xhook
// Jaime Pillora <dev#jpillora.com> - MIT Copyright 2018
(function (a, b) { var c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H = [].indexOf || function (a) { for (var b = 0, c = this.length; b < c; b++)if (b in this && this[b] === a) return b; return -1 }; q = null, q = "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope ? self : "undefined" != typeof global ? global : a, x = q.document, d = "before", c = "after", o = "readyState", n = "addEventListener", m = "removeEventListener", h = "dispatchEvent", u = "XMLHttpRequest", g = "fetch", i = "FormData", p = ["load", "loadend", "loadstart"], e = ["progress", "abort", "error", "timeout"], E = "undefined" != typeof navigator && navigator.useragent ? navigator.userAgent : "", A = parseInt((/msie (\d+)/.exec(E.toLowerCase()) || [])[1]), isNaN(A) && (A = parseInt((/trident\/.*; rv:(\d+)/.exec(E.toLowerCase()) || [])[1])), (G = Array.prototype).indexOf || (G.indexOf = function (a) { var b, c, d, e; for (b = d = 0, e = this.length; d < e; b = ++d)if (c = this[b], c === a) return b; return -1 }), D = function (a, b) { return Array.prototype.slice.call(a, b) }, w = function (a) { return "returnValue" === a || "totalSize" === a || "position" === a }, z = function (a, b) { var c; for (c in a) if (a[c], !w(c)) try { b[c] = a[c] } catch (a) { } return b }, B = function (a) { return void 0 === a ? null : a }, C = function (a, b, c) { var d, e, f, g; for (e = function (a) { return function (d) { var e, f, g; e = {}; for (f in d) w(f) || (g = d[f], e[f] = g === b ? c : g); return c[h](a, e) } }, f = 0, g = a.length; f < g; f++)d = a[f], c._has(d) && (b["on" + d] = e(d)) }, y = function (a) { var b; if (x && null != x.createEventObject) return b = x.createEventObject(), b.type = a, b; try { return new Event(a) } catch (b) { return { type: a } } }, f = function (a) { var c, d, e; return d = {}, e = function (a) { return d[a] || [] }, c = {}, c[n] = function (a, c, f) { d[a] = e(a), d[a].indexOf(c) >= 0 || (f = f === b ? d[a].length : f, d[a].splice(f, 0, c)) }, c[m] = function (a, c) { var f; if (a === b) return void (d = {}); c === b && (d[a] = []), f = e(a).indexOf(c), f !== -1 && e(a).splice(f, 1) }, c[h] = function () { var b, d, f, g, h, i, j, k; for (b = D(arguments), d = b.shift(), a || (b[0] = z(b[0], y(d))), g = c["on" + d], g && g.apply(c, b), k = e(d).concat(e("*")), f = i = 0, j = k.length; i < j; f = ++i)h = k[f], h.apply(c, b) }, c._has = function (a) { return !(!d[a] && !c["on" + a]) }, a && (c.listeners = function (a) { return D(e(a)) }, c.on = c[n], c.off = c[m], c.fire = c[h], c.once = function (a, b) { var d; return d = function () { return c.off(a, d), b.apply(null, arguments) }, c.on(a, d) }, c.destroy = function () { return d = {} }), c }, F = f(!0), F.EventEmitter = f, F[d] = function (a, b) { if (a.length < 1 || a.length > 2) throw "invalid hook"; return F[n](d, a, b) }, F[c] = function (a, b) { if (a.length < 2 || a.length > 3) throw "invalid hook"; return F[n](c, a, b) }, F.enable = function () { q[u] = t, "function" == typeof r && (q[g] = r), k && (q[i] = s) }, F.disable = function () { q[u] = F[u], q[g] = F[g], k && (q[i] = k) }, v = F.headers = function (a, b) { var c, d, e, f, g, h, i, j, k; switch (null == b && (b = {}), typeof a) { case "object": d = []; for (e in a) g = a[e], f = e.toLowerCase(), d.push(f + ":\t" + g); return d.join("\n") + "\n"; case "string": for (d = a.split("\n"), i = 0, j = d.length; i < j; i++)c = d[i], /([^:]+):\s*(.+)/.test(c) && (f = null != (k = RegExp.$1) ? k.toLowerCase() : void 0, h = RegExp.$2, null == b[f] && (b[f] = h)); return b } }, k = q[i], s = function (a) { var b; this.fd = a ? new k(a) : new k, this.form = a, b = [], Object.defineProperty(this, "entries", { get: function () { var c; return c = a ? D(a.querySelectorAll("input,select")).filter(function (a) { var b; return "checkbox" !== (b = a.type) && "radio" !== b || a.checked }).map(function (a) { return [a.name, "file" === a.type ? a.files : a.value] }) : [], c.concat(b) } }), this.append = function (a) { return function () { var c; return c = D(arguments), b.push(c), a.fd.append.apply(a.fd, c) } }(this) }, k && (F[i] = k, q[i] = s), l = q[u], F[u] = l, t = q[u] = function () { var a, b, g, i, j, k, l, m, q, r, t, w, x, y, D, E, G, I, J, K, L; a = -1, I = new F[u], t = {}, y = null, l = void 0, D = void 0, w = void 0, r = function () { var b, c, d, e; if (w.status = y || I.status, y === a && A < 10 || (w.statusText = I.statusText), y !== a) { e = v(I.getAllResponseHeaders()); for (b in e) d = e[b], w.headers[b] || (c = b.toLowerCase(), w.headers[c] = d) } }, q = function () { if (I.responseType && "text" !== I.responseType) "document" === I.responseType ? (w.xml = I.responseXML, w.data = I.responseXML) : w.data = I.response; else { w.text = I.responseText, w.data = I.responseText; try { w.xml = I.responseXML } catch (a) { } } "responseURL" in I && (w.finalUrl = I.responseURL) }, G = function () { k.status = w.status, k.statusText = w.statusText }, E = function () { "text" in w && (k.responseText = w.text), "xml" in w && (k.responseXML = w.xml), "data" in w && (k.response = w.data), "finalUrl" in w && (k.responseURL = w.finalUrl) }, i = function (a) { for (; a > b && b < 4;)k[o] = ++b, 1 === b && k[h]("loadstart", {}), 2 === b && G(), 4 === b && (G(), E()), k[h]("readystatechange", {}), 4 === b && (t.async === !1 ? g() : setTimeout(g, 0)) }, g = function () { l || k[h]("load", {}), k[h]("loadend", {}), l && (k[o] = 0) }, b = 0, x = function (a) { var b, d; if (4 !== a) return void i(a); b = F.listeners(c), (d = function () { var a; return b.length ? (a = b.shift(), 2 === a.length ? (a(t, w), d()) : 3 === a.length && t.async ? a(t, w, d) : d()) : i(4) })() }, k = t.xhr = f(), I.onreadystatechange = function (a) { try { 2 === I[o] && r() } catch (a) { } 4 === I[o] && (D = !1, r(), q()), x(I[o]) }, m = function () { l = !0 }, k[n]("error", m), k[n]("timeout", m), k[n]("abort", m), k[n]("progress", function () { b < 3 ? x(3) : k[h]("readystatechange", {}) }), ("withCredentials" in I || F.addWithCredentials) && (k.withCredentials = !1), k.status = 0, L = e.concat(p); for (J = 0, K = L.length; J < K; J++)j = L[J], k["on" + j] = null; return k.open = function (a, c, d, e, f) { b = 0, l = !1, D = !1, t.headers = {}, t.headerNames = {}, t.status = 0, w = {}, w.headers = {}, t.method = a, t.url = c, t.async = d !== !1, t.user = e, t.pass = f, x(1) }, k.send = function (a) { var b, c, f, g, h, i, j, l; for (l = ["type", "timeout", "withCredentials"], i = 0, j = l.length; i < j; i++)c = l[i], f = "type" === c ? "responseType" : c, f in k && (t[c] = k[f]); t.body = a, h = function () { var a, b, d, g, h, i; for (C(e, I, k), k.upload && C(e.concat(p), I.upload, k.upload), D = !0, I.open(t.method, t.url, t.async, t.user, t.pass), h = ["type", "timeout", "withCredentials"], d = 0, g = h.length; d < g; d++)c = h[d], f = "type" === c ? "responseType" : c, c in t && (I[f] = t[c]); i = t.headers; for (a in i) b = i[a], a && I.setRequestHeader(a, b); t.body instanceof s && (t.body = t.body.fd), I.send(t.body) }, b = F.listeners(d), (g = function () { var a, c; return b.length ? (a = function (a) { if ("object" == typeof a && ("number" == typeof a.status || "number" == typeof w.status)) return z(a, w), H.call(a, "data") < 0 && (a.data = a.response || a.text), void x(4); g() }, a.head = function (a) { return z(a, w), x(2) }, a.progress = function (a) { return z(a, w), x(3) }, c = b.shift(), 1 === c.length ? a(c(t)) : 2 === c.length && t.async ? c(t, a) : a()) : h() })() }, k.abort = function () { y = a, D ? I.abort() : k[h]("abort", {}) }, k.setRequestHeader = function (a, b) { var c, d; c = null != a ? a.toLowerCase() : void 0, d = t.headerNames[c] = t.headerNames[c] || a, t.headers[d] && (b = t.headers[d] + ", " + b), t.headers[d] = b }, k.getResponseHeader = function (a) { var b; return b = null != a ? a.toLowerCase() : void 0, B(w.headers[b]) }, k.getAllResponseHeaders = function () { return B(v(w.headers)) }, I.overrideMimeType && (k.overrideMimeType = function () { return I.overrideMimeType.apply(I, arguments) }), I.upload && (k.upload = t.upload = f()), k.UNSENT = 0, k.OPENED = 1, k.HEADERS_RECEIVED = 2, k.LOADING = 3, k.DONE = 4, k.response = "", k.responseText = "", k.responseXML = null, k.readyState = 0, k.statusText = "", k }, "function" == typeof q[g] && (j = q[g], F[g] = j, r = q[g] = function (a, b) { var e, f, g; return null == b && (b = { headers: {} }), b.url = a, g = null, f = F.listeners(d), e = F.listeners(c), new Promise(function (a, c) { var d, h, i, k, l; h = function () { return b.body instanceof s && (b.body = b.body.fd), b.headers && (b.headers = new Headers(b.headers)), g || (g = new Request(b.url, b)), z(b, g) }, i = function (b) { var c; return e.length ? (c = e.shift(), 2 === c.length ? (c(h(), b), i(b)) : 3 === c.length ? c(h(), b, i) : i(b)) : a(b) }, d = function (b) { var c; if (void 0 !== b) return c = new Response(b.body || b.text, b), a(c), void i(c); k() }, k = function () { var a; return f.length ? (a = f.shift(), 1 === a.length ? d(a(b)) : 2 === a.length ? a(h(), d) : void 0) : void l() }, l = function () { return j(h()).then(function (a) { return i(a) }).catch(function (a) { return i(a), c(a) }) }, k() }) }), t.UNSENT = 0, t.OPENED = 1, t.HEADERS_RECEIVED = 2, t.LOADING = 3, t.DONE = 4, "function" == typeof define && define.amd ? define("xhook", [], function () { return F }) : "object" == typeof module && module.exports ? module.exports = { xhook: F } : q && (q.xhook = F) }).call(this, window);
// Extract the {name} value from the cookies (used to find token)
function check_cookie_name(name) {
debugger;
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) {
return match[2];
}
else {
console.log('-- try to call API without authentication token ---');
return "Please login"
}
}
// Add token in header before each request
xhook.before(function (request) {
request.headers['token'] = check_cookie_name('token');
});
The actual result is good, and it works.
I expect to find a better/cleaner way to do the same thing ^^
Thank you in advance,
Regards
Nicolas

Check for Anagram in 2 strings

I've created a function that checks if 2 words are anagrams, but I want to make it better. I feel the declaration of the counter after in the if statement is not quite well, if anybody have a better solution would be great.
function checkAnagram(string1, string2){
if(string1.length !== string2.length){
return false;
}
for(var i = 0; i < string1.length; i++){
if(count <= 0){
return false;
}
var count = 0;
for(var t = 0; t < string2.length; t++){
//counter = 0
if(string2[t].toLowerCase() == string1[i].toLowerCase()){
//counter++;
count++;
break;
}
}
}
return true;
}
Here is a much easier way of doing it:
var s1 = "test"
var s2 = "tset"
function testAnagram (s1, s2){
if(!s1 || !s2 || s1.length !== s2.length){return false;}
var lS1 = s1.toLowerCase();
var lS2 = s2.toLowerCase();
if(lS1 === lS2) {return false;}
var rS1 = lS1.split('').sort().join('');
var rS2 = lS2.split('').sort().join('');
return rS1 === rS2;
}
var result = testAnagram(s1, s2);
alert(result);
Your code returns true for strings 'aabb' and 'abcc', which are not anagrams. You can just sort the strings and check if they're equal:
function checkAnagram(string1, string2) {
return string1.toLowerCase().split("").sort().join("") === string2.toLowerCase().split("").sort().join("")
}
function checkAnagram(string1, string2) {
return string1.replace(/[^\w]/g,'').toLowerCase().split('').sort().join('') ===
string2.toLowerCase().replace(/[^\w]/g,'').split('').sort().join('')
}
If you don't want to use prebuild methods like .split() .sort() .join() then
function isAnagrams(stringA, stringB) {
// just to remove special char and convert it to lowercase
stringA = stringA.replace(/[^\w]/g, "").toLowerCase();
stringB = stringB.replace(/[^\w]/g, "").toLowerCase();
if (stringA.length !== stringB.length) return false;
let aCharMap = {};
let bCharMap = {};
/*
making of mapObject of both string, containing character as property and
count of that character as value
*/
for (let i = 0; i < stringA.length; i++) {
bCharMap[stringB[i]] = bCharMap[stringB[i]] + 1 || 1;
aCharMap[stringA[i]] = aCharMap[stringA[i]] + 1 || 1;
}
// checking both CharMap value
for (let q of stringB) {
if (bCharMap[q] !== aCharMap[q]) {
return false;
}
}
return true;
}
console.log(`isAnagram : ${isAnagrams('rail safety', 'fairy tales')}`)
so if you pass isAnagrams('rail safety','fairy tales'); then character map will look like this
aCharMap = { r: 1, a: 2, i: 1, l: 1, s: 1, f: 1, e: 1, t: 1, y: 1 }
bCharMap = { f: 1, a: 2, i: 1, r: 1, y: 1, t: 1, l: 1, e: 1, s: 1 }
then we will compare if they have same value or not based on that result will be decided
function isAnagram(str1, str2){
if(str1.length !== str2.length){
return false
}
let string1 = str1.toLowerCase().split('').sort().join('');
let string2 = str2.toLowerCase().split('').sort().join('');
return string1 === string2
}
isAnagram('abcdef', 'AbcFed')

How to sort JavaScript string array

I have the following array:
var arr = ["COL10","COL5",
"COL4","COL3",
"COL8","COL9",
"COL2","COL7",
"COL1","COL6"];
console.log("After sort:"+arr.sort());
The output is:
After sort:COL1,COL10,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9
But I want it to be:
After sort:COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10
How should I do this?
Use the following approach with Array.sort and String.slice functions:
var arr = ["COL10","COL5","COL4","COL3","COL8","COL9","COL2","COL7","COL1","COL6"];
arr.sort(function (a,b) {
return a.slice(3) - b.slice(3);
});
console.log(arr);
You could split the items and sort the parts separate.
var arr = ["COL10", "COL5", "COL4", "COL3", "COL8", "COL9", "COL2", "COL7", "COL1", "COL6"];
arr.sort(function (a, b) {
var aa = a.split(/(\d+)/g),
bb = b.split(/(\d+)/g);
return aa[0].localeCompare(bb[0]) || aa[1] - bb[1];
});
console.log(arr);
Try out the alphanumerical sort from Brian Huisman:
Article
var arr = ["COL10", "COL5",
"COL4", "COL3",
"COL8", "COL9",
"COL2", "COL7",
"COL1", "COL6"
];
console.log("After sort:" + arr.sort(alphanum));
function alphanum(a, b) {
function chunkify(t) {
var tz = [],
x = 0,
y = -1,
n = 0,
i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >= 48 && i <= 57));
if (m !== n) {
tz[++y] = "";
n = m;
}
tz[y] += j;
}
return tz;
}
var aa = chunkify(a);
var bb = chunkify(b);
for (x = 0; aa[x] && bb[x]; x++) {
if (aa[x] !== bb[x]) {
var c = Number(aa[x]),
d = Number(bb[x]);
if (c == aa[x] && d == bb[x]) {
return c - d;
} else return (aa[x] > bb[x]) ? 1 : -1;
}
}
return aa.length - bb.length;
}
var arr = ["COL10","COL5",
"COL4","COL3",
"COL8","COL9",
"COL2","COL7",
"COL1","COL6"];
arr.sort(function(a,b) {
var a1 = parseInt(a.split('COL')[1]);
var b1 = parseInt(b.split('COL')[1]);
return a1 - b1;
});

Categories