Otto
Otto

Reputation: 693

VueX Getter to filter unique id's from array

I want to filter an array (that contains objects), to grab each message that contains a unique correspondence_id.

**Store contains 'messages' (with this structure): enter image description here

Getters where I want to filter it.

getCorrespondedUsers: (state) => {
        return state.messages.unique
    }

The messages all contain a correspondence_id, however now I can only grab all the messages, but I want to just grab unique people. The purpose of this is that I have messages, but on the left I want to display each person that I've messaged (but I'm not sure how I can only display each person once).

How can I filter my messages to just return each message with a unique correspondence_id?

Upvotes: 1

Views: 1632

Answers (2)

Vladislav Ladicky
Vladislav Ladicky

Reputation: 2489

You can use lodash to maintain readability of your code. Example:

// don't forget to import only what
// you really need, not the whole library
import uniqBy from 'lodash/uniqBy'

export default {
  getCorrespondedUsers: state => uniqBy(state.messages, 'correspondence_id')
}

Upvotes: 3

LakiGeri
LakiGeri

Reputation: 2105

There is a solution of this problem.

So you can do this:

getCorrespondedUsers: (state) => {
        return state.messages.filter((obj, pos, arr) => {
           return arr.map(mapObj => mapObj["corresponde_id"]).indexOf(obj["corresponde_id"]) === pos;
    });
}

I tested here.

I hope it works!

Upvotes: 2

Related Questions