-2

i have this array:

var arr = ["apple","potato","carrot","tomato","grape","banana","potato","carrot","carrot"];

As you can see, we have "potato" 2 times in this array, and also "carrot" 3 times in this array. How can i create a new array, that will content only "potato" and "carrot" values, so only values that are not single/unique in initial array?

Like this:

["potato","carrot"];

How it can be done in js?

Antony Slahin
  • 31
  • 1
  • 5
  • 5
    Does this answer your question? [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/questions/840781/get-all-non-unique-values-i-e-duplicate-more-than-one-occurrence-in-an-array) – evolutionxbox Mar 10 '22 at 12:58
  • Get familiar with [how to access and process objects, arrays, or JSON](https://stackoverflow.com/q/11922383/4642212) and how to [create objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the static and instance methods of [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Mar 10 '22 at 13:00
  • Thanks, friends. Investigating now – Antony Slahin Mar 10 '22 at 13:03

1 Answers1

0

Check this one liner:

[...new Set(arr.filter(e => arr.filter(a => a === e).length > 1))];

arr.filter(e ...) - filter array for duplicates

[...new Set(...))] - create array with unique values using set and spread syntax

Working snippet:

var arr = ["apple","potato","carrot","tomato","grape","banana","potato","carrot","carrot"];

console.log([...new Set(arr.filter(e => arr.filter(a => a === e).length > 1))]);
stacj
  • 1,103
  • 1
  • 7
  • 20
  • This is what i want, thanks. Found also this solution with the help of people, that shared some links here: `newarr = arr.filter((e, i, a) => a.indexOf(e) !== i);` – Antony Slahin Mar 10 '22 at 13:03
  • No, that isn't what you want. It's unreadable. Use the code in the duplicate question evolutionbox added in the comments. – Andy Mar 10 '22 at 13:05