I have 2 arrays with current week dates and investments with value and date. I want to return an array with the values that have corresponding dates between the 2 arrays.
My non-working solution is:
JavaScript
x
53
53
1
const daysOfWeek = [
2
"20-06-2022",
3
"21-06-2022",
4
"22-06-2022",
5
"23-06-2022",
6
"24-06-2022",
7
"25-06-2022",
8
"26-06-2022",
9
]
10
11
const investmentsData = [{
12
value: 0.77,
13
date: "21-06-2022"
14
},
15
{
16
value: 1.50,
17
date: "22-06-2022"
18
},
19
{
20
value: 0.80,
21
date: "20-06-2022"
22
},
23
{
24
value: 1.00,
25
date: "21-06-2022"
26
},
27
{
28
value: 0.77,
29
date: "20-06-2022"
30
},
31
{
32
value: 0.79,
33
date: "22-06-2022"
34
},
35
{
36
value: 0.73,
37
date: "18-06-2022"
38
},
39
{
40
value: 1.29,
41
date: "19-06-2022"
42
}
43
]
44
45
const result = investmentsData.flatMap((dayValue) => {
46
const getDayValue = daysOfWeek.filter((day) => {
47
return dayValue.date === day;
48
});
49
return getDayValue;
50
});
51
const filteredResult = result.filter((val) => !!val);
52
console.log(filteredResult)
53
// ["21-06-2022", "22-06-2022", "20-06-2022", "21-06-2022", "20-06-2022", "22-06-2022"]
When what I need is:
[0.77, 1.50, 0.80, 1.00, 0.77, 0.79]
Probably the filter inside the map is not the best option as it´s going to return the value of the first array (which is a date).
I also have the problem that result
returns also the undefined. I then run filteredResult
to remove all the undefined in the result. I guess this is a job that can be done with one function all together.
Advertisement
Answer
Take it step by step:
- Filter
investmentsData
on whether or notdaysOfWeek
contains thedate
- From the filtered values, return the
value
.
JavaScript
1
17
17
1
const daysOfWeek = ["20-06-2022", "21-06-2022", "22-06-2022", "23-06-2022", "24-06-2022", "25-06-2022", "26-06-2022"];
2
const investmentsData = [
3
{ value: 0.77, date: "21-06-2022" },
4
{ value: 1.50, date: "22-06-2022" },
5
{ value: 0.80, date: "20-06-2022" },
6
{ value: 1.00, date: "21-06-2022" },
7
{ value: 0.77, date: "20-06-2022" },
8
{ value: 0.79, date: "22-06-2022" },
9
{ value: 0.73, date: "18-06-2022" },
10
{ value: 1.29, date: "19-06-2022" }
11
]
12
13
const result = investmentsData
14
.filter(d => daysOfWeek.includes(d.date))
15
.map(d => d.value);
16
17
console.log(result);