Stack Overflow Asked by crimsonpython24 on November 4, 2021
I was getting started on javascript and I faced difficulties comparing two strings successfully in React (or just Javascript in this case). Say I have the following function:
function compare(a, b) {
var n = -1, m = 0;
console.log(a, b, b === "important"); // prints here
if (a === "important") {n = 2;}
else if (a === "normal") {n = 1;}
else {n = 0;}
if (b === "important") {m = 2;}
else if (b === "normal") {m = 1;}
else {m = 0;}
return n - m;
}
but the code’s output (after two separate executions) was
["normal"]
["important"] // this case? b is "important"
false
["unimportant"]
["normal"]
false
I can’t see why the code above doesn’t work. Can anyone please explain? Thanks in advance.
EDIT
Function called in
sorter: (a, b) => compare(a.levels, b.levels),
Where a and b are
{
key: "1",
title: "Eat",
date: "2020-07-20 07:57",
levels: ["important"]
},
{
key: "2",
title: "Sleep",
date: "2020-07-20 07:57",
levels: ["normal"]
},
Note that the function is called in React. CodeSandbox Demo
you can use switch statement
function compare (a, b){
function swit(v){
switch (v){
case 'important' :
return 2;
case 'normal' :
return 1
default :
return 0
}
}
return swit(a) - swit(b);
}
var normal = ["normal"];
var important = ["important"]
console.log(compare(normal[0] , important[0]))
console.log(compare(important[0] , important[0]))
console.log(compare(important[0] , normal[0]))
Answered by Moufeed Juboqji on November 4, 2021
Clearly, because a and b are arrays instead of string literals. You should be comparing a[0] in the method or passing in a.levels[0] in the compare method.
Answered by jancha on November 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP