Get the last 30 days from an Array with Dates - javascript

What I am trying to achieve is to get all entries from an array in a range of the last 30 days and push this into a new array which I can work with afterwards.
My array (this.trades) looks like this:
{
id: "95",
datum: "2020-03-11",
trade: "EUR/USD BUY",
aktion: "closed",
pips: "10"
},
{
id: "94",
datum: "2020-06-09",
trade: "GBP/USD BUY",
aktion: "TP Hit",
pips: "65"
},
{
id: "93",
datum: "2020-06-08",
trade: "NZD/USD SELL",
aktion: "SL Hit",
pips: "-57"
},
datum is the german word for date.
the array is pretty long (filled with 95 entries over the past half year).
So my desired output would be:
to sort the Array by its date (this.trades.datum)
to extract all the entries within the last 30 days
and finally push this into a new array to work with (containing all the other keys)
I'm working in a vuejs project and have the opportunity to use computed properties for calculating, i'm also using momentjs library.
Here is my current function, where i convert datum into dateobjects:
But i want to get only the entries from the last 30 days.
chartDatumMonth() {
let data = this.trades;
data.forEach(d => {
d.dateObj = moment(d.datum);
});
console.log(data);
return data;
},
console output:
(80) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0:
aktion: (...)
dateObj: Moment
_d: Wed Aug 05 2020 00:00:00 GMT+0200 (Mitteleuropäische Sommerzeit) {}
_f: "YYYY-MM-DD"
_i: "2020-08-05"
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}
__proto__: Object
datum: "2020-08-05"
id: (...)
pips: (...)
trade: (...)
__ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
get aktion: ƒ reactiveGetter()
set aktion: ƒ reactiveSetter(newVal)
get datum: ƒ reactiveGetter()
set datum: ƒ reactiveSetter(newVal)
get id: ƒ reactiveGetter()
set id: ƒ reactiveSetter(newVal)
get pips: ƒ reactiveGetter()
set pips: ƒ reactiveSetter(newVal)
get trade: ƒ reactiveGetter()
set trade: ƒ reactiveSetter(newVal)
__proto__: Object
1:
aktion: (...)
dateObj: Moment {_isAMomentObject: true, _i: "2020-08-04", _f: "YYYY-MM-DD", _isUTC: false, _pf: {…}, …}
datum: "2020-08-04"

In ECMAScript, dates in the format "YYYY-MM-DD" are parsed as UTC. When creating a date using new Date(), it is based on the local date and also has a component for the current time so when comparing values like "30 days ago" you must normalise everything to the same datum. In this case, UTC will be the simplest.
Otherwise, you'll get errors if the code is run near the start or end of the local day due to timezone offset differences where the UTC date is behind or ahead of the local date. The time component also should be set to zero.
The following creates a date for n days ago, then filters the dataset and sorts it. Since the supplied data is a few months old, I've made daysAgo a parameter that is passed to the function. Also, the sort uses localCompare as it's more efficient than creating and comparing Date objects, and works well with ISO 8601 formatted dates.
let data = [{
id: "95",
datum: "2020-03-11",
trade: "EUR/USD BUY",
aktion: "closed",
pips: "10"
},
{
id: "94",
datum: "2020-06-09",
trade: "GBP/USD BUY",
aktion: "TP Hit",
pips: "65"
}, {
id: "93",
datum: "2020-06-08",
trade: "NZD/USD SELL",
aktion: "SL Hit",
pips: "-57"
}];
function getDaysAgoData(data, daysAgo) {
// Get current date
let t = new Date();
// Create UTC date for daysAgo
let d = new Date(Date.UTC(t.getFullYear(), t.getMonth(), t.getDate() - daysAgo));
// Filter and sort data
return data.filter(item => new Date(item.datum) >= d)
.sort((a, b) => a.datum.localeCompare(b.datum));
}
console.log(getDaysAgoData(data, 90));

This should get you going
const list = [{
id: "95",
datum: "2020-03-11",
trade: "EUR/USD BUY",
aktion: "closed",
pips: "10"
},
{
id: "94",
datum: "2020-06-09",
trade: "GBP/USD BUY",
aktion: "TP Hit",
pips: "65"
},
{
id: "93",
datum: "2020-08-01",
trade: "NZD/USD SELL",
aktion: "SL Hit",
pips: "-57"
},
]
const currentDate = new Date();
const currentDateTime = currentDate.getTime();
const last30DaysDate = new Date(currentDate.setDate(currentDate.getDate() - 30));
const last30DaysDateTime = last30DaysDate.getTime();
const last30DaysList = list.filter(x => {
const elementDateTime = new Date(x.datum).getTime();
if (elementDateTime <= currentDateTime && elementDateTime > last30DaysDateTime) {
return true;
}
return false
}).sort((a, b) => {
return new Date(b.datum) - new Date(a.datum);
});
console.log(last30DaysList)

Edit: Now the array is sorted (in first version I forgot this);
let arr = [{
id: "95",
datum: "2020-03-11",
trade: "EUR/USD BUY",
aktion: "closed",
pips: "10"
},
{
id: "94",
datum: "2020-07-20",
trade: "GBP/USD BUY",
aktion: "TP Hit",
pips: "65"
},
{
id: "93",
datum: "2020-06-18",
trade: "NZD/USD SELL",
aktion: "SL Hit",
pips: "-57"
},
{
id: "92",
datum: "2020-07-15",
trade: "GBP/USD BUY",
aktion: "TP Hit",
pips: "65"
},];
const today = new Date ();
result = arr.filter(obj => {
const date = new Date(obj.datum);
const diffTime = Math.abs(today - date);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return (diffDays <=30);
});
result.sort((a,b) => {
a = new Date(a.datum);
b= new Date(b.datum);
return (a<b) ? -1 : (a>b) ? 1 : 0;
})
console.log(result);

Related

How to loop through and reference with an array in an array?

I have this array and it has an array with different number of elements.
var filtered = [Array(3), Array(1), Array(2), Array(7), Array(1), Array(1), Array(5)]
0: Array(3)
0: {fixture: {…}, league: {…}, teams: {…}, goals: {…}, score: {…}}
1: {fixture: {…}, league: {…}, teams: {…}, goals: {…}, score: {…}}
2: {fixture: {…}, league: {…}, teams: {…}, goals: {…}, score: {…}}
1: [{…}] //1 element
2: (2) [{…}, {…}] //2 elements
3: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] //7 elements
I want to access the data inside through looping so I try to use this:
for (i = 0; i < filtered.length-1; i++) {
for (x=0; x<filtered[i].length-1;x++){
let league = document.createElement("div")
league.className = 'league'
league.innerHTML = filtered[i].x.league.name //error occurs on .league.name
parent.appendChild(league)
}}
and I get this error message:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'league')
I likely am referencing it wrong but do not know how else to do this.

array.filter remove undefined value

I have two arrays. My first array is multidimensional. I am looping over the first array and checking if the index matches HeaderIndex value on an object in my second array. If so I am returning a new array with updated object. However I do not want my returned array to have any undefined values... I tried using array.filter
Here is my code below
const Array1 = [
['Alex', 'Boe', 'MeowWolf', 'pizza', 'pink', 'MeowWolf', 'corsair', 'coarse hair'],
['Arron', 'Coe', 'Kmart', 'tofu', 'purple', 'purr pull'],
['Jane', 'Doe', 'Sears', 'tacos', 'orange', 'Sears', 'see ears'],
['John', 'Eoe', 'YugiOh', 'blueberries', 'magenta'],
['Suzie', 'Boe', 'Toyota', 'steroids', 'blue']
]
const Array2 = [{
header: 'First name',
HeaderIndex: 0
},
{
header: 'Last name',
HeaderIndex: 1
},
{
header: 'Company',
HeaderIndex: 2
},
{
header: 'Favorite food',
HeaderIndex: 3
},
{
header: 'Favorite color',
HeaderIndex: 4
},
]
const testResult = Array1.map(
(arr) => arr.map(
(string, index) => {
if (Array2.filter(
(obj) => obj.HeaderIndex === index)[0])
return {
"ChosenHeader": Array2.filter(
(obj) => obj.HeaderIndex === index),
"content": string
}
}))
console.log(testResult);
I am getting this result
0: (8) [{…}, {…}, {…}, {…}, {…}, undefined, undefined, undefined]
1: (6) [{…}, {…}, {…}, {…}, {…}, undefined]
2: (7) [{…}, {…}, {…}, {…}, {…}, undefined, undefined]
3: (5) [{…}, {…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, {…}, {…}]
But I want something like this
0: (5) [{…}, {…}, {…}, {…}, {…}]
1: (5) [{…}, {…}, {…}, {…}, {…}]
2: (5) [{…}, {…}, {…}, {…}, {…}]
3: (5) [{…}, {…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, {…}, {…}]
I guess you need something like this:
const result = array1.map((arr1, index) => {
if (array2.some((arr2) => arr2.HeaderIndex === index))
return {
ChosenHeader: array2.find(obj => obj.HeaderIndex === index),
content: arr1,
};
});

Add element of array into existing array of objects

I'm struggling with how to add the element of the array into an array of objects. I have an array of object:
0: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
1: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
...etc
And I have an array that contains strings:
const titles = ["some title A", "some title B", "some title C"]
So my purpose is, I want to make my data like this:
[
{results: my_existing_array_of_object, title: "some title A"},
{results: my_existing_array_of_object, title: "some title B"},
{results: my_existing_array_of_object, title: "some title C"},
]
How to do that? Thanks in advance
I do some adjustment from the answer of #StepUp
const titles = ["some title A", "some title B", "some title C"]
const other = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
const result = other.map(((o, i) => ({results: o, //add new key
title: (i < titles.length) ? titles[i] : ''})))
console.log(result )
It is possible to use map function to get desired array:
const titles = ["some title A", "some title B", "some title C"]
const other = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
const result = other.map(((o, i) => ({results: o,
title: (i < titles.length) ? titles[i] : ''})))
console.log(result )

Looping through JSON to grab geo-coordinates (d3 and leaflet)

I've asked this before but simplifying the question. I have a JSON with geo-coordinates that I'd like to map in d3/leaflet:
Here's the structure, when console.logging the JSON allSFEvents:
(36) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
And digging into one item:
#context: "http://schema.org"
#type: "MusicEvent"
endDate: "2019-01-27"
image: ""
location:
#type: "Place"
address: "San Francisco, CA"
geo:
#type: "GeoCoordinates"
latitude: 37.775
longitude: -122.4183333
__proto__: Object
name: "Natoma Cabana"
__proto__: Object
name: "Winter Olympics"
performer: {url: "https://www.bandsintown.com/a/217960-
winter-olympics?came_from=244", image: "", #type:
"MusicGroup", name: "Winter Olympics"}
startDate: "2019-01-27"
url: "https://www.bandsintown.com/e/1013280443-winter-olympics-at-natoma-cabana?came_from=244"
__proto__: Object
When I try to convert to latLong coordinates:
allSFEvents.forEach(function(d) {
d.latLong = new L.LatLng(allSFEvents.location.geo[0],//first position is latitude
allSFEvents.location.geo[1];//second position is longitude
console.log(d.latLong)
})
It gives me an error saying:
Cannot read property 'geo' of undefined
How do I loop through each item and run the L/.LatLong here? I seem to be stuck. The goal is to get distinct lat/long pairs for each item, in order to map it. Thanks in advance.
the forEach-function goes thru every element of your list and the parameter of the function is the one item of the list. So d is one item of your allSFEvents-Array.
https://www.w3schools.com/jsref/jsref_forEach.asp
So try the following:
allSFEvents.forEach(function(d) {
//here replace allSFEEvents with d then location should be set. And replace geo[0] with geo.latitude and geo[1] with geo.longitude because geo is not an array
d.latLong = new L.LatLng(d.location.geo.latitude,//first position is latitude
d.location.geo.longitude;//second position is longitude
console.log(d.latLong)
})

JavaScript: Assign an unique identifier to an array and iterate over objects in the array

I have 4 arrays full of objects:
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(27) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(21) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Each object contains a bit of information, that I want to display to the viewer:
0: Object { exchange: "NYSE", quote: "JPY", price: "3923.76016", … }
​
1: Object { exchange: "DEF", quote: "GBP", price: "3924.60972", … }
​
2: Object { exchange: "FEG", quote: "EUR", price: "3917.31980", … }
​
3: {…}
​​
exchange: "NEX"
​​
price: "3914.70000"
​​
quote: "USD"
​​
timestamp: "2018-12-31T07:47:11.253Z"
​​
<prototype>: Object { … }
How can I
1) Assign a unique value to the array, ie. Array #1 is VTX, Array #2 is DEF, so that when I display it on the page, I don't need to change the ticker symbol (ie. VTX on exchange NEX is $100, and I only need to change the exchange name and currency/amount)
2) iterate over the arrays to where the iterator moves on to the next object in the array, let's say, every 2-3 seconds?
I'm doing this in React and have passed the data on to props, but now I'm stuck trying to figure this out.
1) You can store all your arrays in on object like this :
const myArrays = [
{
uniqueName: 'VTX',
infos: []
},{
uniqueName: 'DEF',
infos: []
}
]
2) You should store the index in the state, and make it change with setInterval in componentDidMount
componentDidMount() {
this.timerID = setInterval(
() => this.nextInfo(),
1000
);
}

Categories

Resources