How to replace return on if condition? - javascript

Is possible to replace by if condition instead using return while we have many condition in our program
var v2=[12,23,44,3,1,3,456,78,22];
function checkresult(v2) {
return v2 >= 18;
}
var a= v2.filter(checkresult);
document.getElementById("demo").innerHTML = a;

Yes, you can obviously use conditional statements inside a filter as long as you're returning a boolean value.
var v2=[12,23,44,3,1,3,456,78,22];
function checkresult(val) { // A suggestion to use different variable name other than v2
if(val >= 18)
return true;
else if(<condition-2>)
return true;
else if(<condition-n>)
return true;
return false;
}
var a= v2.filter(checkresult);
document.getElementById("demo").innerHTML = a;

Yes, it is possible
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
var a = [1,2,'a','b','a',1,'c'];
var unique = a.filter(onlyUnique);
As example this code, onlyUnique function is return unique values in array. You can change the function content.

Related

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array

My code is running except for mutation([“Mary”, “Army”]) should return true, but it is returning false and
mutation([“Mary”, “Aarmy”]) should return true, but it is returning false.
Can someone please explain why this is happening?
My code so far
function mutation(arr) {
a=arr.slice(0,1); var a_str = a.toString(); a_arr = Array.from(a_str);
b=arr.slice(1,2); var b_str = b.toString(); b_arr = Array.from(b_str);
var flag=0;
for(var i=0;i<b_arr.length;i++){
for(var j=0;j<a_arr.length;j++){
if(b_arr[i]==a_arr[j]){
flag+=1;
}
}
}
if(flag>=b_arr.length){
return true;
} else return false;
}
console.log(mutation(["Mary", "Aarmy"]));
Problem :
The problem with your code is that JavaScript is case-sensitive while your code doesn't expect that so here is what you can do :
Solution :
if both are equal in that case :
then you can basically do anagram check :
anagram = _ => _.toLowerCase().split('').sort().join('').trim();
const isAnagram = _ => anagram(_[0]) === anagram(_[1])
Other wise you can do something along these lines :
check = a => !a[0].split ``.map(_ => _[X = `toLowerCase`]()).filter(_ => !a[1].includes(_[X]())).length
console.log(check(['Mary','Aarmy']))
You can do this really simply if you use Set. For example:
const mutation = arr => {
var a = new Set(arr[0].toLowerCase())
var b = new Set(arr[1].toLowerCase())
return [...a].every(ch => b.has(ch))
}
console.log(mutation(["Mary", "Army"]))
console.log(mutation(["Mary", "Aarmy"]))
console.log(mutation(["Mary", "Aary"]))
console.log(mutation(["ab", "abba"]))
console.log(mutation(["voodoo", "no"]))
I still feel like there is some ambiguity in the question, but if exactness was required, you could also just check that the set sizes were equal (as they contain all unique letters)
You can use map, filter and toLowerCase functions to achieve this.
Example:
function mutation(arr){
return !arr[0].split("")
.map(x => x.toLowerCase())
.filter(l => !arr[1].includes(l.toLowerCase())).length
}
var res = mutation(["Mary", "Aarmy"]);
console.log(res); //true
You need to use toLowerCase() to compare each character with case insensitivity. And you can further remove the extra inner loop and do something like this:
function mutation(checkArray){
var firstElement = checkArray[0];
var secondElement = checkArray[1];
var splitSecondElement = secondElement.split('');
var matched = true;
for(var i=0; i<splitSecondElement.length; i++){
var firstElementLower = firstElement.toLowerCase();
var characterLower = splitSecondElement[i].toLowerCase();
if(firstElementLower.indexOf(characterLower) === -1){
matched = false;
break;
}
}
return matched;
}
console.log(mutation(["Mary", "Army"]));
console.log(mutation(["Mary", "Aarmy"]));
console.log(mutation(["Mary", "Aarmyxyz"]));
var yes;
function mutation(arr){
arr[1]=arr[1].toLowerCase();
arr[0]=arr[0].toLowerCase();
for (var i=0; i<a[1].length; i++){
if(!(arr[0].includes(arr[1].charAt(i))){
return yes= false;
}
else{
yes= true;
}
}
console.log(yes);
}
mutation(["hello","hey"]);

Javascript run a function against a variable usnig dot notation

I think I'm using the wrong terminology but here is what I would like to do. Using a function like this one:
function isNumeric(){
if (isNaN(this)) { return false; }
var x = parseFloat(this);
return (x | 0) === x;
};
I know this function won't work as is. I removed the parameter that was originally passed in and replaced it inside the function with this. I would like to call it like so:
var tmp1 = 10;
var tmp2 = "10";
if( tmp1.isNumeric() == true && tmp2.isNumeric() == true ){
...
}
Instead of this:
if( isNumeric(tmp1) == true && isNumeric(tmp2) == true ){
...
}
The way to achieve that is not considered a good option, but it's to modify the prototype chain for the types of data you want your function to work with, e.g. for number and string like your example you could have:
Number.prototype.isNumeric = String.prototype.isNumeric = function() {
// ...
}
What you have currently is the preferred option because it won't contaminate the prototype chain for inbuilt types, risk conflicts with other libraries, potentially overwrite functionality you didn't know existed, etc. You could meet halfway with something like:
class Val {
constructor(value) {
this.value = value;
}
isNumeric() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
}
Used like:
var tmp1 = new Val(10);
var tmp2 = new Val('10');
console.log(tmp1.isNumeric(), tmp1.isNumeric());
try to add this function to Object.prototype
Object.prototype.isNumeric = function () {
return parseFloat(this) == this;
};
Below may be a better option for the class function if you are wanting "10" to return that is it not a number.
isNumeric() {
return typeof this.value === 'number';
}
isNumeric is just a function - what you are looking for is an object method. Right now, tmp1 and tmp2 are a Number, and String respectively, and neither of those have a function called isNumeric. You can restructure those variables like this if you want:
function TmpValue (initValue) {
this.value = initValue
}
TmpValue.prototype.isNumeric = function() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
var tmp1 = new TmpValue(10);
var tmp2 = new TmpValue('10');

The "return" statement

I had a question about the return statement that is by itself in the control flow.
var rockPaperScissors = function(n) {
var rounds = n;
var results = [];
var weapons = ['rock', 'paper', 'scissors'];
var recurse = function(roundsLeft, played) {
if( roundsLeft === 0) {
results.push(played);
return;
}
for(var i = 0; i<weapons.length; i++) {
var current = weapons[i];
recurse( roundsLeft-1, played.concat(current) );
}
};
recurse(rounds; []);
return results;
}
I was wondering why the return statement is not written as:
return results.push(played);
Is there any benefits? If so, why and when should you write it that way?
That's because recurse is only being used for its side-effects (namely, for what it does to results), not its value. The return is still necessary so that the recursion bottoms out, but other than that, there is no reason to return anything from recurse.
return; is the same as return undefined;, so basically return nothing.
It is the same effect as if the function would finish without a return statement.
return results.push(played); returns the result of results.push(played);, which may not be undefined.
If you ignore the return value of your function recurse, there is no difference, which is the case in your function rockPaperScissors.

Javascript object array sort returns apparantly random results

I am trying to get a simple sort working on an object array but it seems to be returning completely random results. Please have a look at this plunk: (in FF or Chrome)
http://plnkr.co/edit/TqoyUJV4nzvC4hAkVRkz?p=preview
var data;
var asc;
function init(){
data = [{username:"leonhaas"},{username:"0johnson"},{username:"leonlang"},{username:"0lechner"},{username:"0koller"},{username:"leonwinkler"},{username:"0schmidt"},{username:"0mueller"},{username:"0schmid"},{username:"lillyfuchs"},{username:"alexandragruber"},{username:"alexanderlechner"},{username:"alexanderpichler"},{username:"alexandraeder"},{username:"lillyreiter"},{username:"alibauer"},{username:"alexandrahall"},{username:"alexandrajohnson"},{username:"alexandrataylor"},{username:"alexandrawilliams"},{username:"lilywinkler"},{username:"alinabauer"},{username:"aliceegger"},{username:"alicesteiner"},{username:"alicewallner"},{username:"aliegger"},{username:"alifuchs"},{username:"linajohnson"},{username:"amarwhite"},{username:"alinaleitner"},{username:"alinaschmidt"},{username:"alinawood"},{username:"alischneider"}];
outputData(data);
asc = true;
}
function sortIt()
{
a = data.username;
b = data.username;
if(asc){
data.sort(function(a,b)
{
return 1;
});
} else {
data.sort(function(a,b)
{
return -1;
});
}
outputData(data);
}
function outputData(data){
var output = "";
data.forEach(function (item){
output += item.username +"<br>";
});
var x=document.getElementById("demo");
x.innerHTML=output;
}
In your sorting function you have to compare data objects' usernames:
function sortIt()
{
if(asc){
data.sort(function(a,b)
{
return a.username.localeCompare(b.username);
});
} else {
data.sort(function(a,b)
{
return b.username.localeCompare(a.username);
});
}
outputData(data);
}
A couple of things, you're not sorting the array, you need to return 0 if the values are the same, and then -1 (or 1) depending onascending/descending sorting.
Apart from that, you're assigning var a and var b in your sortIt function, true enough, but those aren't the values you'll be using in the sort callback. Because the arguments of the callback are the same name, they mask the a and b variables of the higher scope.
All things considered, the sort callback should look like this:
data.sort(function(a,b)
{
return a.username === b.username ? 0 : a.username >b.username ? 1 : -1;
});
All things considered, your code can do with a lot more work: you're using global variables all over the place, your sortIt function will redeclare the sorting callbacks on each call, you're binding event handlers in HTML (always best to manage JS listeners in JS, sort-of Single Responsability-Principle), calling functions that could benefit from an actual relevant call-context etc... look into IIFE's to create closures for a start, and bookmark MDN
You should return the value from the sort function based on the condition and not just 1 or -1. Like this...
// Inside your script.js. Line #14
if(asc){
data.sort(function(a,b)
{
return a>b ? 1 : -1;
});
} else {
data.sort(function(a,b)
{
return a>b ?-1 : 1;
});
}
function sortIt()
{
a = data.username;
b = data.username;
if(asc){
data.sort(function(a,b)
{
if(a.username.localeCompare(b.username) > 0)
return 1;
else
return -1;
});
} else {
data.sort(function(a,b)
{
if(b.username.localeCompare(a.username) > 0)
return 1;
else
return -1;
});
}
outputData(data);
}
data = [{username: "leonhaas"},...];
var asc = true;
data.sort(function(a, b) {
if (asc)
return a.username > b.username ? 1 : -1;
else
return a.username > b.username ? -1 : 1;
});
for (var i = 0; i < data.length; i++) {
console.log(data[i].username);
}

Javascript Function to split and return a value from a string

I am trying to grab a certain value. I am new to javascript and I can't figure out why this is not working.
If I parse "kid_2" I should get "kostas". Instead of "Kostas" I always get "02-23-2000". So I must have a logic problem in the loop but I am really stuck.
function getold_val(fieldname,str){
var chunks=str.split("||");
var allchunks = chunks.length-1;
for(k=0;k<allchunks;k++){
var n=str.indexOf(fieldname);
alert(chunks[k]);
if(n>0){
var chunkd=chunks[k].split("::");
alert(chunkd);
return chunkd[1];
}
}
}
var test = getold_val('kid_2','date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||');
alert(test);
A regex may be a little more appealing. Here's a fiddle:
function getValue(source, key){
return (new RegExp("(^|\\|)" + key + "::([^$\\|]+)", "i").exec(source) || {})[2];
}
getValue("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","kid_2");
But if you want something a little more involved, you can parse that string into a dictionary like so (fiddle):
function splitToDictionary(val, fieldDelimiter, valueDelimiter){
var dict = {},
fields = val.split(fieldDelimiter),
kvp;
for (var i = 0; i < fields.length; i++) {
if (fields[i] !== "") {
kvp = fields[i].split(valueDelimiter);
dict[kvp[0]] = kvp[1];
}
}
return dict;
}
var dict = splitToDictionary("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","||","::");
console.log(dict["date_1"]);
console.log(dict["date_2"]);
console.log(dict["kid_1"]);
console.log(dict["kid_2"]);​
This works, here's my fiddle.
function getold_val(fieldname,str) {
var chunks = str.split('||');
for(var i = 0; i < chunks.length-1; i++) {
if(chunks[i].indexOf(fieldname) >= 0) {
return(chunks[i].substring(fieldname.length+2));
}
}
}
alert(getold_val('kid_2', 'date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||'));
The issue with your code was (as #slebetman noticed as well) the fact that a string index can be 0 because it starts exactly in the first letter.
The code is almost the same as yours, I just didn't use the second .split('::') because I felt a .substring(...) would be easier.
There are two bugs. The first error is in the indexOf call:
var n = str.indexOf(fieldname);
This will always return a value greater than or equal to 0 since the field exists in the string. What you should be doing is:
var n = chunks[k].indexOf(fieldname);
The second error is in your if statement. It should be:
if(n >= 0) {
...
}
or
if(n > -1) {
...
}
The substring you are looking for could very well be the at the beginning of the string, in which case its index is 0. indexOf returns -1 if it cannot find what you're looking for.
That being said, here's a better way to do what you're trying to do:
function getold_val(fieldName, str) {
var keyValuePairs = str.split("||");
var returnValue = null;
if(/||$/.match(str)) {
keyValuePairs = keyValuePairs.slice(0, keyValuePairs.length - 1);
}
var found = false;
var i = 0;
while(i < keyValuePairs.length && !found) {
var keyValuePair = keyValuePairs[i].split("::");
var key = keyValuePair[0];
var value = keyValuePair[1];
if(fieldName === key) {
returnValue = value;
found = true;
}
i++;
}
return returnValue;
}

Categories

Resources