[Vuejs]-Iterating through list creating new unique list

2👍

The steps could be to get all the unique entity from your array. I am doing this using sets as sets can only store unique values. And then using .map again to convert it to array of objects.

var setDataRaw = this.nluDataUnfiltered.map(
  (el) => {
    if (el.entities.length == 0)
      return [];

    return el.entities.map(
      (_entity) => {
        return _entity.entity;
      }
    )
  });

var setData = [].concat.apply([], setDataRaw);
var uniqueEntity = Array.from(new Set(setData));

var uniqueEntityObj = uniqueEntity.map((el) => {
  return {
    entityName: el,
    entityColor: Util.getRandomColor()
  };
});

1👍

Following the same @void’s idea of creating an Array of unique entities from a Set, here you have his same code but using the spread operator and array reduce to create the full Array of entities.

let uniqueEntityObj = Array.from(
    new Set(
        nluDataUnfiltered.reduce(
            (a, o) => (
                [...a, ...(o.entities.map(so => so.entity))]
            ),
            []
        )
    )
).map(p => ( {entityName: p, entityColor: Util.getRandomColor()} ));

Here you have the compact (and less readable) version:

let uniqueEntityObj = Array.from(new Set(nluDataUnfiltered.reduce((a, o) => ([...a, ...(o.entities.map(so => so.entity))]), []))).map(p => ({entityName: p, entityColor: Util.getRandomColor() }));

Leave a comment