【问题标题】:How can I create a dynamic array based on another array in javascript/typescript?如何在 javascript/typescript 中基于另一个数组创建动态数组?
【发布时间】:2023-02-20 17:29:00
【问题描述】:

我想创建一个数组来遍历第一个数组的一个参数(在这个例子中,所需的参数是DT)并检查我们是否有这些日期不同应用程序的数据。如果我们有它,它会把它的值(在第二个数组中),如果我们没有它,它会把 0。

我所做的也是const pluck = (arr, key) => arr.map(i => i[key]);,我获得了所需的字段日期(但它们有重复的值)。为了删除重复值,我使用了 dates = [...new Set(dates)]; 并最终遍历最终值并编写了一系列代码,但我没有得到我想要的(下面的预期数组)。

first_array = [
  {
    DT: "2022-01-01",
    APP: "Application 1",
    SPEED: 1547,
  },
  {
    DT: "2022-01-01",
    APP: "Application 2",
    SPEED: 685,
  },
  {
    DT: "2022-01-02",
    APP: "Application 1",
    SPEED: 500,
  },
  {
    DT: "2022-01-02",
    APP: "Application 2",
    SPEED: 300,
  },
  {
    DT: "2022-01-02",
    APP: "Application 3",
    SPEED: 600,
  },
  {
    DT: "2022-01-03",
    APP: "Application 1",
    SPEED: 1000,
  },
]

预期数组:

desire_array = [
  {
    Name: "Application1",
    Values: [1547, 500, 1000],
    ValuesWithDate: [{x: '2022-01-01', y: 1547}, {x: '2022-01-02', y: 500}, {x: '2022-01-03', y: 1000}],
  },
  {
    Name: "Application2",
    Values: [685, 300, 0],
    ValuesWithDate: [{x: '2022-01-01', y: 685}, {x: '2022-01-02', y: 300}, {x: '2022-01-03', y: 0}],
  },
  {
    Name: "Application3",
    Values: [0, 600, 0],
    ValuesWithDate: [{x: '2022-01-01', y: 0}, {x: '2022-01-02', y: 600}, {x: '2022-01-03', y: 0}],
  },
]

我需要这样做的原因是创建一个 series,我可以用它来显示带有 ApexCharts 的图表。

真实数据也可以从this api 显示为 JSON。

【问题讨论】:

  • 您采摘日期的方法看起来不错。您使它们独一无二的方法看起来不错。然后你“写了代码”并且“没有得到我想要的”。这就是问题中需要的内容。请编辑以添加 MRE。
  • @danh 我试图在问题中创建预期的数组,但我做不到,我很困惑。我在很多方面打成平手。我的意思是没有得到我想要的东西。编辑。

标签: javascript arrays typescript charts series


【解决方案1】:

你可以做:

const first = [{DT: '2022-01-01',APP: 'Application 1',SPEED: 1547,},{DT: '2022-01-01',APP: 'Application 2',SPEED: 685,},{DT: '2022-01-02',APP: 'Application 1',SPEED: 500,},{DT: '2022-01-02',APP: 'Application 2',SPEED: 300,},{DT: '2022-01-02',APP: 'Application 3',SPEED: 600,},{DT: '2022-01-03',APP: 'Application 1',SPEED: 1000,}]

const dates = [...new Set(first.map(({ DT }) => DT))]
const apps = [...new Set(first.map(({ APP }) => APP))]

const result = apps.reduce((acc, app) => {
  const appData = Object.assign(
    {},
    {
      Name: app.replace(/ /, ''),
      Values: [],
      ValuesWithDate: [],
    }
  )

  dates.forEach((date) => {
    const data = first.find(({ DT, APP }) => DT === date && APP === app)
    appData.ValuesWithDate.push({ x: date, y: data ? data.SPEED : 0 })
    appData.Values.push(data ? data.SPEED : 0)
  })

  acc.push(appData)
  return acc
}, [])

console.log(result)

【讨论】:

    【解决方案2】:

    你可以尝试这样的事情:

    const convertArray = (arr) => arr.reduce((prev, current) => {
        const existingIndex = prev.findIndex((p) => p.Name === current.APP);
      if (existingIndex > -1) {
        const currentApp = prev[existingIndex];
        currentApp.Values.push(current.SPEED);
        currentApp.ValuesWithDate.push({x: current.DT, y: current.SPEED});
        prev[existingIndex] = currentApp;
      } else {
        prev.push({Name: current.APP, Values: [current.SPEED], ValuesWithDate:[{x: current.DT, y: current.SPEED}]})
      }
        return prev;
    }, []);
    

    并像这样使用它:

    const desire_array = convertArray(first_array)
    

    【讨论】:

      【解决方案3】:
          const convert = (dates, data) => {
          return Object.values(data.reduce((acc, curr) => {
              if (!acc[curr.APP]) {
                  acc[curr.APP] = {
                      name: curr.APP,
                      valuesWithDate: []
                  };
              }
              acc[curr.APP].valuesWithDate.push({
                  x: curr.DT,
                  y: curr.SPEED
              });
              return acc;
          }, {})).map((dataWithoutGaps) => {
              const valuesWithDate = [...new Set(dates)].map(date => {
                  const el = dataWithoutGaps.valuesWithDate.find(e => e.x === date);
                  return {
                      x: date,
                      y: el ? el.y : 0
                  };
              });
              return {
                  ValuesWithDate: valuesWithDate,
                  Values: valuesWithDate.map(e => e.y),
                  Name: dataWithoutGaps.name
              }
          });
      };
      
      
      
      console.log(convert(first_array.map(e => e.DT), first_array));
      

      预期的:

      [{"ValuesWithDate":[{"x":"2022-01-01","y":1547},{"x":"2022-01-02","y":500},{"x":"2022-01-03","y":1000}],"Values":[1547,500,1000],"Name":"Application 1"},{"ValuesWithDate":[{"x":"2022-01-01","y":685},{"x":"2022-01-02","y":300},{"x":"2022-01-03","y":0}],"Values":[685,300,0],"Name":"Application 2"},{"ValuesWithDate":[{"x":"2022-01-01","y":0},{"x":"2022-01-02","y":600},{"x":"2022-01-03","y":0}],"Values":[0,600,0],"Name":"Application 3"}]
      

      【讨论】:

        【解决方案4】:

        您可以通过此代码实现预期的结果。

        let filtered_app = new Set();
        const obj = [];
        
        first_array.forEach(item=>{
          filtered_app.add(item.APP);
        });
        filtered_app.forEach(app =>{
          first_array.forEach(item =>{
            if(item.APP == app){
              const exists = obj.findIndex(elem => elem.Name == app);
              if(exists != '-1'){
                obj[exists].Values.push(item.SPEED);
                obj[exists].ValuesWithDate.push({x: item.DT, y: item.SPEED});
              }
              else{
                obj.push({Name: app, Values: [item.SPEED], ValuesWithDate: [{x: item.DT, y: item.SPEED}]});
              }
            }
          });
        });
        console.log(obj);
        

        希望能帮助到你。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-03
          • 1970-01-01
          • 2019-05-02
          • 2018-05-06
          • 2021-07-02
          • 2022-01-03
          相关资源
          最近更新 更多