-2

My question is simple. The array is claimed by a variable.

var array = [1,1,2,2,2,3,3,,4];

How can I get the new array like

array2 = [1,2,3,4] 
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Barry
  • 15
  • 4
  • *"My question is simple"* I cannot see how when I have no idea what you are talking about. What do you think you mean be "coding in mongodb"? Is this an array within a document? Are you actually somehow referring to values in different documents in an abstract way? If you just walked up to someone with that written on a piece of paper, then do you really think they would have any idea what you mean? You need to be a lot more clear when communicating with other people. – Neil Lunn Sep 01 '17 at 00:43
  • Hi, the array is not within document. Only claimed to variable. This question do not involve collection or document. Thank you. – Barry Sep 01 '17 at 01:15
  • 1
    If it has nothing to do with either of those then you are asking about a programming language. There is no "mongodb programming language". You probably mean JavaScript, and you probably mean "within the mongo shell" which is just a JavaScript REPL of course. And when someone says "Your question is unclear" then they ( me actually ) really do mean it and you should pay attention and edit your question to explain what you mean. Of course if you want a "distinct array in JavaScript" then that's the question you ask instead. Or better yet search for it, since it's already been answered. – Neil Lunn Sep 01 '17 at 01:20
  • 2
    Are you asking how to eliminate all repeated values, or all _sequential_ repeated values? Should `[3, 2, 2 3]` be returned as `[3, 2, 3]` or `[3, 2]` (or even `[2, 3]`)? – Michael Lorton Sep 01 '17 at 01:27
  • 1
    Have you seen this https://stackoverflow.com/questions/5381621/jquery-function-to-get-all-unique-elements-from-an-array – The Sammie Sep 01 '17 at 01:29
  • 1
    I'm guessing you didn't even search Google or Stackoverflow before asking this question. – fubar Sep 01 '17 at 01:39
  • One liner ~ `array2 = Array.from(new Set(array)).filter(t => typeof t !== 'undefined')` – Phil Sep 01 '17 at 01:57

1 Answers1

0

This might help (Unique values in an array). This answer is from above link

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}

usage example:

var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']
Akira Yamamoto
  • 4,685
  • 4
  • 42
  • 43
y2501
  • 73
  • 6