I need to get the closest date from an array of dates with DateFNS v.2.0.1 closestIndexTo. I'm currently getting NaN returned. What am I missing here?
(val = 2019-09-01)
(arrDates = 2019-09-01,2019-09-03,2019-09-03,2019-09-04,2019-09-05,2019-09-05,2019-09-23,2019-10-01,2019-11-18)
getClosestToDate(val,arr) {
var arrDates = [_.map(arr, 'date')]
var closestDate = closestIndexTo(parseISO(val), arrDates)
return closestDate
},
So basically dates should be strings in first place. Next probably incorrect place is where you use [_.map(arr, 'date')] which actually place result of map into array making it double array. Also in order to parse arr into Date objects you need map arr values to parseISO function. So following code should work
var closestIndexTo = require('date-fns/closestIndexTo')
var parseISO = require('date-fns/parseISO')
var _ = require('lodash')
val = "2019-10-04"
arrDates = ["2019-09-01","2019-09-03","2019-09-03","2019-09-04","2019-09-05","2019-09-05","2019-09-23","2019-10-01","2019-11-18"]
function getClosestToDate(val, arr) {
var arrDates = _.map(arr, (a) => parseISO(a))
var closestDate = closestIndexTo(parseISO(val), arrDates)
return closestDate
}
console.log("result", getClosestToDate(val, arrDates))
Here is link to repl
Related
let bdays = ["10-17", "05-19", "20-19"];
how do i change the '-' in that array to '/'.
You could also use Array.map to create a new array of formatted values
let bdays = ["10-17", "05-19", "20-19"];``
let formattedBdays = bdays.map((date) => {
return date.replace('-','/')
});
console.log(formattedBdays);
Gives Output
['10/17', '05/19', '20/19']
You can learn more about map in the docs here
let bdays = ["10-17", "05-19", "20-19"];``
for( let bday of bdays) {
bdays[bdays.indexOf(bday)]= bday.replace('-','/');
}
I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.
I'm using app script
I have Return array from API by this code :
const price= jsonResponce.price.map(obj => [obj[0],obj[1]]);
Give me [[30.56, 1.014], [50.44, 1.019], [10.35, 1.081], [10.34, 1.115], [10.40, 2.006]]
Not this array can be has 1000 array or large
Now I want to sum all object in obj[0] by using this code :
I use to method to see the deference but nothing work
var first= [];
var second= 0;
price.forEach(function(obj){
first+= obj[0];
second+= obj[1];
});
Logger.log(first);
Logger.log(second);
But Give me result like that: first Logger.log(first);
30.5650.4410.3510.3410.40
second Logger.log(second); : this method add number 0 after any obj
01.01401.01901.08101.11502.006
Any idea for this problem
30.56+50.44+10.35+10.34+10.40
I need result as : 112.09
Your code works fine for me, after minimal corrections:
const price = [[30.56, 1.014], [50.44, 1.019], [10.35, 1.081], [10.34, 1.115], [10.40, 2.006]]
var first = 0; // <-- here
var second = 0;
price.forEach(obj => {
first += +obj[0]; // <-- here
second += +obj[1]; // <-- here
});
console.log(first); // --> 112.09
console.log(second); // --> 6.2349
You can get four digits after dot this way:
var a = 1.23456789;
var b = 1234.56789;
var c = 16643.59000000003
const dot1000 = x => Math.round(x*10000)/10000;
console.log(dot1000(a));
console.log(dot1000(b));
console.log(dot1000(c));
Another implementation (with zeros at the end)
var a = 1.23456789
var b = 1234.56789
var c = 16643.59000000003
const dot1000 = x => parseInt(x) + '.' + (x+.00001+'').split('.')[1].slice(0,4)
console.log(dot1000(a))
console.log(dot1000(b))
console.log(dot1000(c))
Update
Modern JavaScript (ES2017) can add zeros this way:
console.log('123'.padEnd(5,'0')); // 12300
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
numbersInArray = price.flat()
let sum = 0
numbersInArray.forEach( number => sum += number)
Using Array.prototype.reduce() method, this becomes very easy:
const result = arr.reduce((total, el)=> {
return total + el[0] + el[1] // el = [a, b]
}, 0)
console.log(result) /// 118.325
Let me know in the comments if this is what you want or you want any improvements
You are adding the array in which each number (both obj[0] and obj[1] values) is treated as String type. So that's why they are not added like numbers but concatenated. First convert the String Type into Number. Then your problem will be resolved.
As I don't know about the used API. So I could not give answer with API response included. But I am giving you code where I do some changes but just look at the praseFloat() method that I used.
const Api_Response_Array = [["30.56", "1.014"], ["50.44", "1.019"], ["10.35", "1.081"], ["10.34", "1.115"], ["10.40", "2.006"]];
var first= 0;
var second= 0;
Api_Response_Array.forEach(function(){
first+= parseFloat(Api_Response_Array[0][0]);
second+= parseFloat(Api_Response_Array[0][1]);
});
document.write(first + "<br>");
document.write(second);
Just use praseFloat method inside function used within forEach loop. It will convert the string into number.
I really need your help,
I would like to be able to check and see if a variable matches an array value and return true if it does.
ie.
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
alert("true")
I was thinking of using this approach, but for the life of me, I cannot get it to return true, ideas?
function test() {
var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
if ( $.inArray('ASFA', arr) > -1 ) {
alert("true")
}
}
Try as follows
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
array.forEach(function(ele){
console.log(ele.includes(x));
})
Quick and easy with ES6 :
let x = "ASFA",
array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"],
found = array.some(elem => elem.includes(x))
console.log(found)
I have an array of items in Javascript similar to the following:
var data =
[
{"id":"338b79f07dfe8b3877b3aa41a5bb8a58","date":"2000-10-05T13:21:30Z","value": {"country":"United States"}},
{"id":"338b79f07dfe8b3877b3aa41a5bb983e","date":"2000-02-05T13:21:30Z","value":{"country":"Norway"}},
{"id":"338b79f07dfe8b3877b3aa41a5ddfefe","date":"2000-12-05T13:21:30Z","value":{"country":"Hungary"}},
{"id":"338b79f07dfe8b3877b3aa41a5fe29d7","date":"2000-05-05T13:21:30Z","value":{"country":"United States"}},
{"id":"b6ed02fb38d6506d7371c419751e8a14","date":"2000-05-05T18:15:30Z","value":{"country":"Germany"}},
{"id":"b6ed02fb38d6506d7371c419753e20b6","date":"2000-12-05T18:15:30Z","value":{"country":"Hungary"}},
{"id":"b6ed02fb38d6506d7371c419755f34ad","date":"2000-06-05T18:15:30Z","value":{"country":"United States"}},
{"id":"b6ed02fb38d6506d7371c419755f3e17","date":"2000-04-05T22:15:30Z","value":{"country":"Germany"}},
{"id":"338b79f07dfe8b3877b3aa41a506082f","date":"2000-07-05T22:15:30Z","value":{"country":"United Kingdom"}},
{"id":"9366afb036bf8b63c9f45379bbe29509","date":"2000-11-05T22:15:30Z","value":{"country":"United Kingdom"}}
];
I need to query (reduce) the array by the date. Either greater than or less than a pre-determined date eg. current date.
I was thinking of using Underscores reduce method to do this. Can anybody provide an example of how I could do this?
Edit: I trying something like this:
var itemsByDate = _(items).reduce(function(memo, item) {
memo[item.date] = memo[item.date] || [];
memo[item.date].push(item);
return memo;
}, {});
console.log((JSON.stringify(itemsByDate["2000-11-05T22:15:30Z"])));
But this looks for an exact match and will probably not deal with the dates properly because they are strings.
Regards,
Carlskii
If you want to filter the set, you can do this:
var reduced = data.filter(function(obj) {
var date = +(new Date(obj.date));
return date < someDate || date > someOtherDate
});
If you wanted to reduce it to a pair of sets, you can do this:
var now = Date.now();
var reduced = data.reduce(function(ret, obj) {
var date = +(new Date(obj.date));
if (date < now)
ret.before.push(obj);
else
ret.onOrAfter.push(obj);
return ret;
}, {before:[], onOrAfter:[]});