Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
  });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading