Home > Blockchain >  Filter data from arrays
Filter data from arrays

Time:12-18

What I need is to sort data I get from an API into different arrays but add '0' value where there is no value at 1 type but is at the other type/s. Now is this possible with array.filter since its faster then a bunch of for and if loops ?

So let's say I get following data from SQL to the API:

Day        Type  Amount
-----------------------
12.1.2022  1     11
12.1.2022  2     4
13.1.2022  1     5
14.1.2022  2     9
16.1.2022  2     30

If I run this code :

this.data = result.Data;
let date = [];
const data = { 'dataType1': [], 'dataType2': [], 'dataType3': [], 'dataType4': [] }

/*only writing example for 2 types since for 4 it would be too long but i desire 
answer that works for any amount of types or for 4 types */

this.data.forEach(x => {
  var lastAddress = date[date.length - 1]
  if (x.type == 1) {dataType1.push(x.Amount) }
  if (x.type == 2) {dataType2.push(x.Amount) }}
  lastAddress != x.Day ? date.push(x.Day) : '';

The array I get for type1 is [11,5] and for type2 I get [4,9,30]. And for dates i get all the unique dates

But the data I would like is: [11,5,0,0] and [4,0,9,30] The size of array also has to match the size of Day array at the end. which would be unique dates.. in this case:

[12.1.2022, 13.1.2022, 14.1.2022, 16.1.2022]

I have already tried to solve this with some for, if and while loops but it gets way too messy, so I'm looking for an alternative

Also i have 4 types but for reference i only wrote sample for 2

CodePudding user response:

const type1 = [];
const type2 = [];

data.forEach(item=>{
  if(item.type==1){
   type1.push(item.amount)
   type2.push(0)
  }else{
   type1.push(0)
   type2.push(item.amount)
  }
})
console.log(type1)
console.log(type2)

CodePudding user response:

you can

  1. first get the uniq values
  2. loop over the data to create an array of object with {date:string,values:number[]}
  //create a function:

  matrix(data:any[])
  {
    const  uniqTypes=data.reduce((a,b)=>a.indexOf(b.type)>=0?a:
                     [...a,b.type],[])
    const result=[]
    this.data.forEach((x:any)=>{
      let index=result.findIndex(r=>r.date==x.date)
      if (index<0)
      {
        result.push({date:x.date,values:[...uniqTypes].fill(0)})
        index=result.length-1;
      }
      result[index].values[uniqTypes.indexOf(x.type)]=x.amount
    })
    return result
  }

  //and use like
  result=this.matrix(this.data);

NOTE: You can create the uniqType outside the function as variable and pass as argument to the function

stackblitz

  • Related