How to optimise sum of values from array with exact value from array of objects?

I have an array of objects

[ 
    { hashtag: [ 'yo' ], type: [] },
    { hashtag: [ 'yo2' ], type: [] },
    { hashtag: [ 'yo3' ], type: [] },
    { hashtag: [ 'yo4' ], type: [] },
    { hashtag: [ 'yo4' ], type: [] },
    { hashtag: [ 'yo5' ], type: [ 'email' ] },
    { hashtag: [ 'yo5' ], type: [ 'link' ] },
    { hashtag: [ 'asdasdasd' ], type: [ 'email' ] },
    { hashtag: [ 'yo5' ], type: [ 'link' ] },
    { hashtag: [ 'yo6' ], type: [ 'link' ] },
    { hashtag: [ 'yo6' ], type: [ 'link' ] },
    { hashtag: [ 'yo7' ], type: [ 'link' ] },
    { hashtag: [ 'book', 'hello', 'yo5' ], type: [ 'link' ] } 
];

Each hashtag value can contain array of strings. I need to get all array of unique hashtags which have exact type and count them. Result should look like this

[ 
    { hashtag: 'yo5', sum: 3 },
    { hashtag: 'yo6', sum: 2 },
    { hashtag: 'yo7', sum: 1 },
    { hashtag: 'book', sum: 1 },
    { hashtag: 'hello', sum: 1 } 
]

I wrote code, but it seems for me that it is not enough optimised. Is there way to make it better?

const type = 'link';

const enter = [ 
    { hashtag: [ 'yo' ], type: [] },
       ...
    { hashtag: [ 'book', 'hello', 'yo5' ], type: [ 'link' ] } 
];

const filteredByType = enter.filter((el) => {
    return el.type.includes(type)
});

const newArr = [];

Here is working example

filteredByType.map((el) => {
  for (let i = 0; i < el.hashtag.length; i++) {
    const z = newArr.filter((e) => {
        return e.hashtag === el.hashtag[i]
    });
    if (z.length) {
      const p = newArr.findIndex((obj) => {
        return obj.hashtag === el.hashtag[i];
      });
      newArr[p].sum += 1;
    } else {
      newArr.push({
        hashtag: el.hashtag[i],
        sum: 1
      })
    }
  }
});

console.log('newArr', newArr);

121 thoughts on “How to optimise sum of values from array with exact value from array of objects?”

Leave a Comment