0

In couchdb i have a array field:

numbers:["79998887766","79998887755","79998887766","79998887744"]

In node.js app i want to have only unique numbers.Like this:

["79998887766","79998887755","79998887744"]

Its possible to do with couchdb view or node.js module cradle?
Or only way get all numbers and filter array with node?

Kliver Max
  • 5,107
  • 22
  • 95
  • 148

3 Answers3

1

it's fairly straightforward, if inelegant, to iterate across the array twice testing for duplicates. since this is O(n²) it won't scale well for big arrays; i would look for a more sophisticated solution if you expect your numbers array to contain hundreds or more items

function testExists(item, arr2){
  var exists = false;
  arr2.forEach(function(item2){
    if(item === item2){
      exists = true;
    } 
  });
  return exists;
};

function removeDupes(arr){
  var output = [];
  arr.forEach(function(item){
    var exists = testExists(item, output);
    if(!exists){
      output.push(item);
    };
  });
  return output;
};

console.log(removeDupes(["a","b","a","c"]));
Plato
  • 10,812
  • 2
  • 41
  • 61
1

I believe there is no native command for implementing this in CouchDB. A possible solution for the problem would be to make use of something like redis sets. There are also a few third party libraries that implement sets in Javascript like this one : https://github.com/PeterScott/simplesets-nodejs.

Amal Antony
  • 6,477
  • 14
  • 53
  • 76
1

You can do either in CouchDB view or in node.js code after fetching data. In both cases you'll need to write javascript code to exclude duplicates. You can use objects of this:

var obj = {};

numbers.forEach(function (num) {
    obj[num] = true;
});

var unique = Object.keys(obj);

It works if order of keys doesn't matter. Doing this in a view is a better way, since the results of computation will be reused.

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
  • i can't find an authoritative reference but I was under the impression that you can't (or shouldn't?) use a leading number as a javascript identifiers, see e.g. http://coderkeen.com/old/articles/identifiers-en.html – Plato Oct 15 '13 at 17:18
  • Here it is http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, page 18, but these rules don't work with square bracket notation. – vkurchatkin Oct 15 '13 at 17:27