Mdd
Mdd

Reputation: 4420

Filter array of objects into new array

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)
    });

Upvotes: 0

Views: 140

Answers (3)

Lander Van Breda
Lander Van Breda

Reputation: 873

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.

Upvotes: 1

Urielzen
Urielzen

Reputation: 506

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

Upvotes: 1

royhowie
royhowie

Reputation: 11171

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"];

Upvotes: 1

Related Questions