英文:
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 "|" (pipe). 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 an array_merge
and 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);
});
});
英文:
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);
});
});
答案1
得分: 1
你需要循环遍历split()
返回的数组中的所有元素。最简单的方法是使用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);
});
});
英文:
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
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
});
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论