JavaScript .map() syntax error - javascript

new to JS.
I'm using google script to create a function that will input a string will output the interger in it (if any). In order to optimize for google script, I've read suggestions on allowing also ranges as input.
I'm getting an error when using .map, but I can't figure out what it is. Any help. I've been looking for more examples of the use of map but none were helpfull.
Any idea?
thanks everyone
if (input.map) {
input.map(
if (isInt(split[i])) {
result = split[i]
});
} else {
for (i = 0; i < split.length; i++) {
if (isInt(split[i])) {
result = split[i];
}
}
}

To .map you should pass function as parameter,
input.map(function() {
// your code
});

will input a string will output the interger in it (if any)
Try using isNaN , Number() , Array.prototype.filter() , typeof to return Number values
var arr = ["1", "a", "0"];
var res = arr.map(function(n) {
return !isNaN(Number(n)) && Number(n)
}).filter(function(n) {
return typeof n === "number"
});
console.log(res)

Related

how to get value from object with a partial index value javascript

I have an object which contains alot of keys and values. I can get any value using the index. But I dont have the full index, I have a part of it, would I be able to get the value based on a part of the index.
Example:
c = {'select':'MyValue',...}
I can get the value using indexing as shown below:
c['select'] = 'MyValue'
I tried to create this function which searches exact value:
function search(nameKey, c){
for (var i=0; i < c.length; i++) {
if (c[i].select === nameKey) {
return c[i];
}
}
}
c['select'] will return 'MyValue' but I need to do something like c['Sel'] or c['select'] or c['Select']or c['selected']to return the same 'MyValue'
Well the logic doesn't seem to be very clear and it's not quite relevant how it would be matching the key.
But This is a function that may help in the specific cases you showed:
function search(nameKey, obj) {
if (obj.hasOwnProperty(nameKey)) {
return obj[nameKey];
} else {
var res = Object.keys(obj).filter(function(k) {
return (k.toLowerCase().indexOf(nameKey.toLowerCase()) > -1) || (nameKey.toLowerCase().indexOf(k.toLowerCase()) > -1);
});
return res ? obj[res] : false;
}
}
Explanation:
First we use Object#hasOwnProperty() to check if the object has the searched name as key/property, we return it's value, this will avoid looping all the keys.
Otherwise we use Object.keys() to get the keys of the object.
Then we use Array#filter() method over the keys array to check if a relevant key exists we
return it's value, otherwise we return false.
Demo:
function search(nameKey, obj) {
if (obj.hasOwnProperty(nameKey)) {
return obj[nameKey];
} else {
var res = Object.keys(obj).filter(function(k) {
return (k.toLowerCase().indexOf(nameKey.toLowerCase()) > -1) || (nameKey.toLowerCase().indexOf(k.toLowerCase()) > -1);
});
return res ? obj[res] : false;
}
}
var c = {
'select': 'MyValue'
};
console.log(search("Sel", c));
Here's an one liner (!):
Assuming your array is in data and the partial index value is in selector:
const result = Object.keys(data).filter(k => k.toLowerCase().indexOf(selector.toLowerCase()) != -1).map(k => data[k]);
The above code returns an Array (coz, there may be more than one match). If you just need a first element, just do result[0].
You can use Object.keys() to get an array of the property names.
Then find first match using Array#find() to get the key needed (if it exists)
const data = {
aaaa: 1,
bbbbbbb: 2,
cccc: 3
}
function search(nameKey, obj) {
nameKey = nameKey.toLowerCase();// normalize both to lowercase to make it case insensitive
const keys = Object.keys(obj);
const wantedKey = keys.find(key => key.toLowerCase().includes(nameKey));
return wantedKey ? obj[wantedKey] : false;
}
console.log('Term "a" value:', search('a',data))
console.log('Term "bb" value:', search('bb',data))
console.log('Term "X" value:', search('X',data))
Since search criteria is vague I simply found any match anywhere in the property name and didn't look past the first one found

eval is not calculate if zero before the number

var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
for (var i=0; i<values.length; i++) {
if(values[i].indexOf('+')>0 || values[i].indexOf('-')>0 || values[i].indexOf('*')>0 || values[i].indexOf('/')>0){
try{
var evaluated = eval(values[i]);
if(typeof evaluated === 'number'){
console.log(evaluated);
}
}catch (e){
console.error(e)
}
}
}
I have some math actions, it's could be plus, minus or other actions, and I need to take result for this actions. I use eval for this. But if I have zero before number like 005,75 eval is not working. How can I calculate this?
You can split the strings and parse the numbers, and then make them into a string again to use eval
var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
values.forEach(function(value){
var newValue = value.split(/([\+\-\*\/])/).map(a => parseFloat(a) || a).join('');
var evaluated = eval(newValue);
console.log(value,"==", evaluated);
});
There are various libraries like math.js that can be used to evaluate expressions:
console.log(math.eval("0050.00024+040.04005+0.1"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.5/math.min.js"></script>
you should convert it to float (ex. parseFloat("005.75") = 5.75 instead of evaluating strings
Given code at Question you can use .match() to get number values, .map() and .reduce() to add the values
var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
var res = values.map(function(n) {
return n.match(/[\d.]+/g).reduce(function(a, b) {
return a + Number(b)
}, 0)
});
console.log(res);

For loop not giving proper result

var integer = 10;
var plus = [];
for(var i = 2; i < integer; i++) {
if(integer % i === 0){
plus.push[i];
}
}
console.log(plus)
this prints empty array, but why? shoudnt it print [2, 5]? I cant find what is wrong in my code
this works :
var integer = 10;
var plus = [];
for (var i = 2; i < integer; i++) {
if (integer % i === 0) {
plus.push(i);
}
}
console.log(plus)
so, basically what you were doing wrong is using .push[i]. its a common syntax error. you just need to use .push(i)
plus.push(i); instead of using plus.push[i];
Functions are objects in JavaScript. plus.push[i]; looks up a property on push, the function object, using i's value as the name (exactly like indexing into an array); and then throws away whatever value it got (presumably undefined, as the function probably doesn't have properties named "2", "4", etc.). That's why you're not getting a syntax error, as you would in many other languages.
To call push, use (), not []:
plus.push(i);

How can I rewrite the .length() property using slice()?

This is my assignment:
By now you should have worked with the length property of strings, e.g. "hello".length. Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!
Instead, you'll need to make use of the string method called slice.
For our purposes, we can consider slice as taking one argument -- the index to begin slicing from, and returns a new string starting from that index onwards.
This is what I tried:
function stringLength(string){
var count = count++;
if(string.slice(0)){
return count}
return stringLength(string.slice(0,-1))
}
console.log(stringLength("game"))
I am trying to slice each character of the string back to start index, index 0, and then accumulate my count variable. I do not understand why my count variable is not accumulating.
An iterative proposal.
function stringLength(string) {
var count = 0;
while (string) {
string = string.slice(1);
count++;
}
return count;
}
console.log(stringLength("game"));
A recursive proposal.
function stringLength(string) {
return string ? 1 + stringLength(string.slice(1)) : 0;
}
console.log(stringLength("game"));
Hmm i tried to write code in the same format that you did.
function stringLength(str, count){
if(!str.slice(0)){
return count;
}
return stringLength(str.slice(0,-1), ++count)
}
console.log(stringLength("game", 0))
I'll point out the mistakes in your original code so that its easy to understand.
The recursion base case was incorrect. string.slice(0) will return
true if the string is non-empty, so use !string.slice(0)
The count value was not initialized and it wasn't being passed down
the recursion.
Your count variable is a separate variable for each function invocation, so it will always get the same value and not keep incrementing.
You could use this:
function stringLength(string){
return string ? 1 + stringLength(string.slice(0,-1)) : 0;
}
console.log(stringLength("game"))
A bit shorter would be to take out the first character instead of the last:
return string ? 1 + stringLength(string.slice(1)) : 0;
You really should try to figure it out yourself. Otherwise, are you really learning the subject?
function stringLength(string) {
if(!string) return 0;
var length = -1;
while(string.slice(length) !== string) --length;
return -length;
}
A variation taking into account your odd definition of slice():
function stringLength(string) {
var length = 0;
while(string.slice(length) !== "") ++length;
return length;
}
I guess you could try to use recursion like this:
function stringLength(string) {
if (string) {
return 1 + stringLength(string.slice(1))
} else return 0
}
function stringLength(string) {
var len = 0;
while (string) {
string = string.substring(1);
len++;
}
return len;
}
console.log(stringLength("boss"));
this works as well.

convert array of numbers in array of strings using map

im using lodash, and im trying to convert a array of numbers in strings, but only convert the numbers since in my array there are null values. I tried using map of lodash in than map from javascript but is messing up the null values.
Example of array:
[1245, 5845, 4585, null, null]
code:
var meds = _.map(lines,'med_id').map(String);
Result: ["1245", "5845", "4585", "null", "null"];
Should be: ["1245", "5845", "4585", null, null];
You need to test the type of the value before calling String
var meds = _.map(lines, 'med_id').map(function(x) {
return typeof x == 'number' ? String(x) : x;
});
That's because String will convert anything it takes into a string. You need to make a custom function that only generates a string if the value isn't null.
_.map(lines, 'med_id').map(function(x) {
if (x !== null) {
x = x.toString();
}
return x;
});
In looking at: https://lodash.com/docs#map
it looks like:
function toInts(n){
if(isNaN(n)){
return null;
}else{
return n;
}
}
_.map(lines,'med_id').map(lines,toInts);
would do the trick.
(Not Tested)

Categories