Home > Net >  How to filter one array with another array values and return a key value of the first array
How to filter one array with another array values and return a key value of the first array

Time:06-23

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:

const daysOfWeek = [
  "20-06-2022",
  "21-06-2022",
  "22-06-2022",
  "23-06-2022",
  "24-06-2022",
  "25-06-2022",
  "26-06-2022",
]

const investmentsData = [{
    value: 0.77,
    date: "21-06-2022"
  },
  {
    value: 1.50,
    date: "22-06-2022"
  },
  {
    value: 0.80,
    date: "20-06-2022"
  },
  {
    value: 1.00,
    date: "21-06-2022"
  },
  {
    value: 0.77,
    date: "20-06-2022"
  },
  {
    value: 0.79,
    date: "22-06-2022"
  },
  {
    value: 0.73,
    date: "18-06-2022"
  },
  {
    value: 1.29,
    date: "19-06-2022"
  }
]

const result = investmentsData.flatMap((dayValue) => {
  const getDayValue = daysOfWeek.filter((day) => {
    return dayValue.date === day;
  });
  return getDayValue;
});
const filteredResult = result.filter((val) => !!val);
console.log(filteredResult)
// ["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.

CodePudding user response:

Take it step by step:

  1. Filter investmentsData on whether or not daysOfWeek contains the date
  2. From the filtered values, return the value.

const daysOfWeek = ["20-06-2022", "21-06-2022", "22-06-2022", "23-06-2022", "24-06-2022", "25-06-2022", "26-06-2022"];
const investmentsData = [
  { value: 0.77, date: "21-06-2022" },
  { value: 1.50, date: "22-06-2022" },
  { value: 0.80, date: "20-06-2022" },
  { value: 1.00, date: "21-06-2022" },
  { value: 0.77, date: "20-06-2022" },
  { value: 0.79, date: "22-06-2022" },
  { value: 0.73, date: "18-06-2022" },
  { value: 1.29, date: "19-06-2022" }
]

const result = investmentsData
  .filter(d => daysOfWeek.includes(d.date))
  .map(d => d.value);

console.log(result);

  • Related