0

I have an array of objects that contains information for rows. I am trying to filter this information so that I get a new array containing each row value only once. So the following object would output an array like so ['1', '2', '3']

Here is my code. I am trying the map function but not sure if this is the right approach:

var myArray = [
    {
        "row": 1,
        "headline": "First Object"
    },
    {
        "row": 1,
        "headline": "Second Object"
    },
    {
        "row": 2,
        "headline": "Third Object"
    },
    {
        "row": 2,
        "headline": "Fourth Object"
    },
    {
        "row": 3,
        "headline": "Fifth Object"
    }
];
    
    var rows = myArray.map(function(row) {
        console.log(row)
    });
Mdd
  • 4,140
  • 12
  • 45
  • 70

3 Answers3

1

The easiest way to do this would probably be to write all the properties to an object, then write them back to an array:

var o = {},
    uniqueArray = [];

myArray.forEach(function (d) {
    o[d.row] = true; // stores the key equal to d.row in the object
});
for (var k in o) {    // loop through all the keys in o
    if (o.hasOwnProperty(k))    // if the object o has that key
        uniqueArray.push(k);    // push it to the array
}
console.log(uniqueArray);
// ["1", "2", "3"];
royhowie
  • 11,075
  • 14
  • 50
  • 67
1

Put all the row values in an array...

var arrayAll = [];
for (var i = 0; i < myArray.length; i++) {
    arrayAll.push(myArray[i].row)
}

Then remove duplicates

var uniqueNames = [];
$.each(arrayAll, function (i, el) {
    if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

console.log(uniqueNames);

see this post for other options to remove duplicates, if you need a non JQuery option. Remove Duplicates from JavaScript Array

Community
  • 1
  • 1
Urielzen
  • 476
  • 7
  • 17
1

For a more readable approach then the chosen answer I would go for :

var distinct = function(rows){
    var mappedValues = rows.map(function(single){
        return single.row;
    });
    return mappedValues.filter(function(item,pos){
        return mappedValues.indexOf(item) === pos;
    });
}

distinct(myArray);

Just my 2 cents.

Lander Van Breda
  • 873
  • 6
  • 12
  • 1
    The only problem being that this is `O(n^2)`. Large datasets will be extremely slow. – royhowie Oct 30 '14 at 06:17
  • @royhowie because I had the same thinking as you, so I made a jsperf to test it out as native functions or sometimes very good optimised. And i got a 3* speed increase against your function even with a larger dataset. http://jsperf.com/filter123 – Lander Van Breda Oct 30 '14 at 10:38
  • @royhowie sorry I have to excuse myself, I made my test case with a large array copying the array didn't think about changing up the numbers. Your solution is indeed in big arrays the better solution. – Lander Van Breda Oct 30 '14 at 11:07
  • yeah, use `Math.random()*10000 |0` and see what happens – royhowie Oct 30 '14 at 16:50