Split string then merge and remove duplicate value in array

I have an API and retrieve the data using jQuery.JSON. I use split to split the locations by "|". And now I’m trying to merge arrays that I’ve split using each in jQuery and remove the duplicates. I already tried concat. Is there a array_merge then array_filter function for javascript/jquery?

Here is my sample code below.

jQuery(document).ready(function($) {
  let get_json = 'https://boards-api.greenhouse.io/v1/boards/frequence/departments/';
  $.getJSON(get_json, function(data) {
    let dept_arr = new Array();
    let arr = new Array();
    let i = 0;
    $.each(data.departments, function(key, value) {
      if (value.jobs.length > 0) {
        $.each(value.jobs, function(key, value) {
          dept_arr[i] = (value.location.name.split('|'));
          i++;
        });
      }
    });
    console.log(dept_arr);
  });
});

>Solution :

You need to loop over all the elements in the array returned by split(). And the easiest way to get rid of duplicates is with a Set.

jQuery(document).ready(function($) {
  let get_json = 'https://boards-api.greenhouse.io/v1/boards/frequence/departments/';
  $.getJSON(get_json, function(data) {
    let dept_set = new Set();
    $.each(data.departments, function(key, dept) {
      $.each(dept.jobs, function(key, job) {
        let locations = job.location.name.split('|');
        $.each(locations, (i, loc) => dept_set.add(loc));
      });
    });
    let dept_arr = [...dept_set]; // convert set to array
    console.log(dept_arr);
  });
});

Leave a Reply