0

I have an array of objects with some properties. If cod and art already exist in the array, I want to remove the repeated ones.

I created a function for this, but my result is wrong... instead of having 3 lines, I have 2.

Can anyone help me?

DEMO

.TS

 data = [
    {
      cod: 1.13,
      art: 'BCC'
    },
    {
      cod: 1.13,
      art: 'BCC'
    },
    {
      cod: 1.13,
      art: 'BCC'
    },
    {
      cod: 1.14,
      art: 'BCC'
    },
    {
      cod: 1.14,
      art: 'BCC'
    },
    {
      cod: 1.13,
      art: 'AAA'
    },
    {
      cod: 1.13,
      art: 'AAA'
    }
  ];

  ngOnInit() {
    var filtered = this.data.filter(function(el) {
      if (!this[el.cod && el.art]) {
        this[el.cod && el.art] = true;
        return true;
      }
      return false;
    }, Object.create(null));
    console.log(filtered);
  }

  //Expected Output

  // data = [
  //   {
  //     cod: 1.13,
  //     art: 'BCC'
  //   },

  //   {
  //     cod: 1.14,
  //     art: 'BCC'
  //   },
  //   {
  //     cod: 1.13,
  //     art: 'AAA'
  //   }
  // ];

3 Answers 3

2

You can use map to achieve your goal

ngOnInit() {
    let map = new Map();

    this.data.forEach(eachItem => map.set(eachItem.cod + '-' + eachItem.art, eachItem));

    console.log('unique items:', Array.from(map.values()));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thats a smooth idea with the map!
1

Try this:

  ngOnInit() {
    var filtered = this.data.filter(function(el) {
      if (!this[el.cod + el.art]) {
        this[el.cod + el.art] = true;
        return true;
      }
      return false;
    }, Object.create(null));
    console.log(filtered);
  }

Comments

0

You can use a set to remember the pushed objects and only add if they are unique.

Here's the edited stackblitz

data = [{
    cod: 1.13,
    art: 'BCC'
  },
  {
    cod: 1.13,
    art: 'BCC'
  },
  {
    cod: 1.13,
    art: 'BCC'
  },
  {
    cod: 1.14,
    art: 'BCC'
  },
  {
    cod: 1.14,
    art: 'BCC'
  },
  {
    cod: 1.13,
    art: 'AAA'
  },
  {
    cod: 1.13,
    art: 'AAA'
  }
];

const unique = data.reduce(((set) => (acc, curr) => {
  const { cod, art } = curr;
  const key = `${cod}_${art}`;
  if (!set.has(key)) {
    set.add(key);
    acc.push(curr);
  }
  return acc;
})(new Set()), []);

console.log(unique)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.