I have array like this structure
["12 18:00", "15 17:30","16 12:00", "12 21:30", "9 10:30"...]
and it has unknown number of elements. I want get every hour:minute for selected element.
Example: if ele=="12" then get 18:00, 21:30. Maybe array has more "12 16:30","12 13:00" etc elements. Then also get 16:30, 13:00. All get elements 18:00, 21:30, 16:30, 13:00
Help me for this solution.
You can do this:
const array = ["12 18:00", "15 17:30","16 12:00", "12 21:30", "9 10:30"];
const getItems = number => {
return array.filter(item => item.split(" ")[0] === number.toString()).map(item => item.split(" ")[1])
}
console.log(getItems(12));
Related
Given the following db structure https://drawsql.app/sensor_network/diagrams/db, I would like to get all sensor_data from a certain location, while grouping the response using station.location, sensor_data.time.
I have the following query:
select
station.location_name,
sensor_data.time,
sensor.type,
sensor_data.value,
sensor.id
from station
inner join
(sensor inner join sensor_data on sensor.id = sensor_data.sensor_id)
on station.sensor_id = sensor.id
where station.location = ?
which gives me the rows I want, however, I would like to format the response in a way where all the rows which share location and time are in the same row. an example output is
location
time
type
value
id
city1
2022-01-01 08:00:00
temperature
290
1
city1
2022-01-01 09:00:00
temperature
292
1
city1
2022-01-01 08:00:00
ph
7
2
city1
2022-01-01 09:00:00
ph
8
2
which I would like to format either like (or similar to)
[
{"location": "city1", "time": "2022-01-01 08:00:00", "temperature": 290, "ph": 7},
{"location": "city1", "time": "2022-01-01 09:00:00", "temperature": 292, "ph": 8},
]
or
[
{"location": "city1", "time": "2022-01-01 08:00:00", "sensors": [{"id": 1, "type": "temperature", "value": 290}, {"id": 2, "type": "ph", "value": 7}]},
{"location": "city1", "time": "2022-01-01 09:00:00", "sensors": [{"id": 1, "type": "temperature", "value": 292}, {"id": 2, "type": "ph", "value": 8}]}
]
Currently, I am doing this formatting in javascript using array functions, but this has proven to be too slow. I have tried using group by query but to be fair, I am struggling to understand how to use that when you don't want to use methods like count etc.
I am using nodejs and its mysql package, the database is mysql:8 and tables are running with innodb engine
You can achieve this with subqueries.
SELECT
st.location,
sd.time,
(
SELECT sd2.value
FROM sensor_data sd2
INNER JOIN sensor s2
ON s2.id = sd2.sensor_id
WHERE sd2.time = sd.time
AND s2.type = "temperature"
) AS temperature,
(
SELECT sd2.value
FROM sensor_data sd2
INNER JOIN sensor s2
ON s2.id = sd2.sensor_id
WHERE sd2.time = sd.time
AND s2.type = "ph"
) AS ph
FROM station st
INNER JOIN sensor s
ON st.sensors = s.id
INNER JOIN sensor_data sd
ON s.id = sd.sensor_id
WHERE st.location = ?
GROUP BY sd.time
Obviously, this will work only if you know the list of types (temperature, ph) in advance and thus you can write separate subqueries for each of them.
If you don't want to build separate subquery for each type, you can concat the values into a single subquery column.
SELECT
st.location,
sd.time,
(
SELECT
GROUP_CONCAT(
CONCAT(s2.type, ':', sd2.value)
SEPARATOR ','
)
FROM sensor_data sd2
INNER JOIN sensor s2
ON s2.id = sd2.sensor_id
WHERE sd2.time = sd.time
GROUP BY sd2.time
) AS sensors
FROM station st
INNER JOIN sensor s
ON st.sensors = s.id
INNER JOIN sensor_data sd
ON s.id = sd.sensor_id
WHERE st.location = ?
GROUP BY sd.time;
Hello I'am new to programming and I stumble upon on grouping array data by date from two arrays.
here is my arrays:
header = [
{"2019-04-22": "Sun, Apr 22, 2019"},
{"2019-04-21": "Sat, Apr 21, 2019"},
]
body = [
{"2019-04-22": "doing customer support”},
{"2019-04-22": "reply to emails"},
{"2019-04-21": "send message to customers"},
]
How do I group the arrays into one array as example below
combinearray = {
"2019-04-22": [
"Sun, Apr 22, 2019",
"doing customer support",
"reply to emails",
],
"2019-04-21": [
"Sat, Apr 21, 2019",
"send message to customers",
],
}
Grouping two array data by date seems completely not easy for me I'm a beginner to javascript programming. I would appreciate any answers.
You can do that in following steps:
First use concat() to combine both arrays i.e header and body
Then use reduce() on that. And pass empty object as second argument(the initial value of accumulator).
In inside reduce() callback use Object.keys()[0] to get date.
Check if the date if date is not already key of accumulator set it to empty [].
Use push() to add the elements to the array.
Note: This will not remove reference to the real object in header and body.
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a)
return ac;
},{})
console.log(res)
However as mentioned in the comments there is no need to have object with keys. Just simple array of the values of that key are enough. For that push() a[key] instead of a.
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a[key])
return ac;
},{})
console.log(res)
You can use combine arrays then use reduce
used spread syntax to merge arrays
use reduce to build an object in desired format
Object.entries to get date and it's respective value
Check if the date is already present as key on object or not, if it's already present push the value to it else create a new key
let header = [{"2019-04-22": "Sun, Apr 22, 2019"},{"2019-04-21": "Sat, Apr 21, 2019"},]
let body = [{"2019-04-22": "doing customer support"},{"2019-04-22": "reply to emails"},{"2019-04-21": "send message to customers"},]
let final = [...header,...body].reduce((op,inp) => {
let [key,value] = Object.entries(inp)[0]
op[key] = op[key] || []
op[key].push(value)
return op
},{})
console.log(final)
I have an array of objects like this
layerArr = [
{
name: "layer 1"
layerDate: "/Date(6958748400000)/"
layerDateFormatted: "31 December 2018"
etc...
}
{
name: "layer 2"
layerDate: "/Date(9375937500000)/"
layerDateFormatted: "23 December 2017"
etc...
}
{
name: "layer 3"
layerDate: "/Date(1554764400000)/"
layerDateFormatted: "15 January 2018"
etc...
}]
How can I sort layerArr by date with the latest date first?
In this example, when layer 2 is sorted correctly, I also want the latest date to become layer 1 and the oldest date should become the last layer. (the example above is made up values)
Thanks
EDIT: the links suggested to other threads do not explain how to change "name" so that the latest date becomes name ="layer 1" all the way to the oldest date becoming the last layer.
Use Array.sort():
layerArr = [
{ name: "layer 1", layerDate: "/Date(6958748400000)/", layerDateFormatted: "31 December 2018" },
{ name: "layer 2", layerDate: "/Date(9375937500000)/", layerDateFormatted: "23 December 2017" },
{ name: "layer 3", layerDate: "/Date(1554764400000)/", layerDateFormatted: "15 January 2018" }
];
sortedLayerArr = layerArr.sort(function(a, b) {
return new Date(a.layerDateFormatted)- new Date(b.layerDateFormatted);
}).map((layer, index) => ({
...layer,
name: `layer ${index + 1}`,
}));
console.log(layerArr);
console.log(sortedLayerArr);
So I have a JSON object of an array of objects that looks something like this:
[
{
"id": 0,
"name": "Sophia Mason",
"availability": [
{
"date": 1522216800000,
"times": ["9:00 am", "2:30 pm", "5:00 pm", "6:00 pm"]
},
{
"date": 1522303200000,
"times": ["9:00 am", "2:30 pm", "5:00 pm", "6:00 pm"]
},
...
],
},
.........
]
I have another array of days rendered using moment.js that looks something like this:
[1522216800000, 1522303200000, 1522389600000]
I need to filter the first array of objects availability by the day in each index of the date array. Then render each photographer in each day correctly in a calendar.
I am using AngularJS (by request of the client) to make something that looks like this:
I already have the days rendering by using Moment, but I am having trouble figuring out how to show each photographer per day based on their availability. To look like the calendar above.
I may be overthinking this but I have been trying to figure this out for the last few hours. Here are some of the many 'similar' answers I have looked through:
Stack
Stack
Stack
Which has me only thinking of something that looks like this in my controller.js:
function setPhotographers() {
let photographer = photographers.filter((el) => {
el.availability.some((availability) => availability.date === today)
.map((el)=> {
console.log(el);
let newEl = Object.assign({}, el);
return newEl.availability.filter(availability => availability.date === today);
});
});
return photographer;
}
I am still am learning a lot but this has me pretty stuck. Any help would be great! Please if you have an answer to describe why your solution works to help me better understand what you did to accomplish this.
Thanks!
You're on the right track with the .filter(), I'm not sure why you need the .map(). The following should be sufficient to get you a filtered array of photographers with availability matching the today variable.
let availablePhotographers = photographers.filter((el) => el.availability.some((availability) => availability.date === today))
I have a javascript object that is coming from Source1 and I am unable to change its native structure or naming convention. I am using this data to feed into a 3rd party plugin to generate some chart data. This plugin however is using the key names as the identifiers on the chart and they are not descriptive or clear enough.
I am trying to run the object through a conversion function where it will change all of the key names to their defined equivalent.
Here is an example of what I am trying to do:
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
function convertNames(obj){
// Converted names
var map = [{
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}];
// Loop through the object and convert all key names to their equivalent
for(var prop in obj){
// Convert Here
}
return obj;
}
Desired Output:
[{
SubmissionIdentifier: "28935",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "No",
},
{
SubmissionIdentifier: "28936",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "Yes",
}]
https://jsfiddle.net/hbg4sfqh/7/
I'd combine the .map array method and a function to convert your key names to get the result you want. To convert the key names, you'll want to use bracket notation, so something like: newObj[keyMap[oldKey]] = oldObj[oldKey] should work.
Here's a simple implementation for your example:
const obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
}, {
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}];
const nameMap = {
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}
function renameKeys(obj, map) {
const newObj = {};
for (let key in obj) {
newObj[map[key]] = obj[key];
}
return newObj;
}
console.log(obj.map(item => renameKeys(item, nameMap)));
I'd also note that if you happen to be using the lodash library, you can also use it's _.mapKeys method to do this.
I'm gonna use .map() function to change the key names. The input data will remain unchanged. Hope this helps.
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
var output = obj.map(element => ({
SubmissionIdentifier: element.SubmissionID,
CreationDate: element.MetaCreatedDate,
ProgramName: element.Program,
Viewed: element.ViewedByInvestigator
}));