skip to Main Content

I am trying to filter a object based on an another array.

data = {
  'TypeA': ['A1', 'A2', 'A3', 'A4'],
  'TypeB': ['B1', 'B2', 'B3', 'B4'],
  'TypeC': ['C1', 'C2', 'C3', 'C4'],
}

array = ['TypeA', 'TypeB']

I want to get a new array with the values of both ‘TypeA’ and ‘TypeB’ like [‘A1’, ‘A2’, ‘A3’, ‘A4’, ‘B1’, ‘B2’, ‘B3’, ‘B4’] and remove duplicates if any also.

so far i have tried,

tTmp_Arr = data.filter(tObj => array.includes(tObj))

Any help is much appreciated.

Thanks in advance.

Thanks,

3

Answers


  1. You can’t use filter on objects. You can get the result by flatmapping and then filtering as:

    const data = {
      'TypeA': ['A1', 'A2', 'A3', 'A4'],
      'TypeB': ['B1', 'B2', 'B3', 'B4'],
      'TypeC': ['C1', 'C2', 'C3', 'C4'],
    };
    
    const array = ['TypeA', 'TypeB'];
    
    const result = array
      .flatMap(key => data[key] || []) 
      .filter((item, index, self) => self.indexOf(item) === index);
      
    console.log(result);
    Login or Signup to reply.
  2. Here’s another working example using array.reduce() with a for..of loop:

    const data =
    {
      'TypeA': ['A1', 'A2', 'A3', 'A4'],
      'TypeB': ['B1', 'B2', 'B3', 'B4'],
      'TypeC': ['C1', 'C2', 'C3', 'C4'],
      
      // EXTRA
      'TypeExtra':
      [
        'A1', 'B1', 'C1',
        'EXTRA VALUE',
      ]
    };
    
    const array = ['TypeA', 'TypeB', 'TypeExtra'];
    
    const result = array.reduce
    (
      ( result, index ) =>
      {
        for ( const item of data[index] )
        {
          if ( ! result.includes(item) )
          {
            result.push(item);
          }
        }
        
        return result;
      },
      []
    );
    
    console.log(result);
    .as-console-wrapper { min-height: 100%; }
    Login or Signup to reply.
  3. Here example using only for..loops

    const data = {
        'TypeA': ['A1', 'A2', 'A3', 'A4'],
        'TypeB': ['B1', 'A1', 'B2', 'B3', 'B4', 'A2'],
        'TypeC': ['C1', 'C2', 'C3', 'C4'],
    }
    
    const checkDublicate = (array, val) => {
        let dublicate = false
        array.forEach((element) => {
            if (element === val) dublicate = true
        })
        return dublicate
    }
    
    const filterFunction = (dataTypes, data) => {
        const temp = []
        for (let i = 0; i < dataTypes.length; i++) {
            const dataBase = data[dataTypes[i]]
            dataBase.forEach(element => {
                const check = checkDublicate(temp, element)
                if (!check) temp.push(element)
            });
        }
        return temp
    }
    
    const dataTypes = ['TypeA', 'TypeB']
    const array = filterFunction(dataTypes, data)
    console.log(array)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search