remove multible years from array

Hi I am creating an array with 10 other arrays using concat. The array is a list of different years. The multiple arrays is creating multiple years for example 2 1998's. How do I only display 1 of each year in my table view. Here is a sample:

alldata = data0.concat (data1, data2, data3, data4, data5, data6, data7, data8, data9, data10, data11, data12, data13, data14, data15);

//sort data by name

//done sort data
function sortByRDate(a, b) {
   var x = a.RDate;
    var y = b.RDate;
   return ((x < y) ? -1 : ((x > y) ? 1 : 0));

//done sort data

//Rdate data to table    

This works but displays multiples of the same year, I would only like to show 1 of each year.

— asked 3 years ago by Rich Carlton
  • I have tried your solution below. If i include the ? i get an error, if I dont include it, i dont get any years in return. Is it possable the loop is writing over its self?

    — commented 3 years ago by Rich Carlton
  • I also tried just creating a new array, Still returns nothing.

    — commented 3 years ago by Rich Carlton

2 Answers

  • Use a javascript object as a hash array. After you concatenate the arrays, make a pass through the years to filter out the unique years. Then put those values back into the alldata array:

    var unique_years = {};
    var i;
    for (i = 0; i < alldata.length; i++)
        var year = alldata[i];
        unique_years[year] = 1;
    alldata = [];
    for (var y in unique_years)
        alldata.push (y);
    — answered 3 years ago by Jason Priebe
    1 Comment
    • Sorry – the "?" at the end is obviously a typo. Remove it, and the code works.

      — commented 3 years ago by Jason Priebe
  • Simply add a unique function to you array objects.

    ####Add the function to the Array JavaScript object

    Array.prototype.unique = function(){
      return this.filter(function(s, i, a){
        return i == a.lastIndexOf(s);

    ####Then use it on your big array

    — answered 3 years ago by Christian Brousseau
    1 Comment
    • Very slick technique. However, if I'm reading the code correctly, that is an O(n^2) operation, whereas my proposed solution should be O(n log n).

      I'm not sure if Rich's arrays are big enough to matter, but obviously, in a mobile app, we have to be cognizant of such things.

      — commented 3 years ago by Jason Priebe