0

My goal is to find all the unique years in this array and than return it as a array. I have almost done it but cant figure out how I will return the split value.

function findUniqueYears() {
  const arr = ['1973-11-01', '2001-01-01', '1999-10-01', '2007-10-01', '2016-06-01', '2005-08-01', '1973-09-01', '1979-12-01', '2001-08-01'];
  for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i].split("-")[0] === arr[j].split("-")[0]) {
        arr.splice(j, 1);
      }
    }
  }
  console.log(arr)
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
matieva
  • 365
  • 4
  • 12
  • Look into using a `Set` for uniqueness. Then you should be able to convert that to an array. – mykaf May 12 '22 at 20:46
  • The problem is that I only wanna find the unique years I don't really care for months and dates and Set will just find unique strings from what I can see – matieva May 12 '22 at 20:48
  • Don't splice an array while you're looping over it. See https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop – Barmar May 12 '22 at 20:50
  • `arr.join(" ").match(/\d{4}/g).filter((a,b,c)=>c.indexOf(a)==b);` – dandavis May 12 '22 at 20:50
  • Put the result in a new array, and return that. – Barmar May 12 '22 at 20:50
  • If your goal is to return the split value, a way to go around it, could be to declare an object and store the splitValue in it, then return the object, which would contain your splitValue when accessed – RoundedHouse May 12 '22 at 20:52
  • You aren't required to enter the entire array element into the `Set`; you can split out the year. – mykaf May 12 '22 at 20:59

2 Answers2

1

This should do

const findUniqueYears = (arr) => Array.from(new Set(arr.map(item => item.split('-')[0])))
callback
  • 3,981
  • 1
  • 31
  • 55
1

You can use the function map to iterate via each element in the array then you can easily split date by '-' return 0 value and cast it to Set.

function findUniqueYears() {
  const arr = ['1973-11-01', '2001-01-01', '1999-10-01', '2007-10-01', '2016-06-01', '2005-08-01', '1973-09-01', '1979-12-01', '2001-08-01'];
  return new Set(arr.map((el) => el.split('-')[0]))
}

Rafał
  • 685
  • 6
  • 13