[英]Find Unique value from an array based on the array's string value (Javascript)
所以我想从数组中找到唯一值。 所以例如我有这个数组:
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
所以我想找到每个唯一项目的第一个匹配值。 例如,在数组中,我有两个带有形状前缀的字符串,六个带有大小前缀的项目,以及两个带有高度前缀的项目。 所以我想输出像
const requiredVal = ["shape-10983", "size-2364", "height-3399"]
我只想要任何一组不同值中的第一个值。
最简单的解决方案是迭代列表并将您得到的内容存储在字典中
function removeSimilars(input) {
let values = {};
for (let value of input) {//iterate on the array
let key = value.splitOnLast('-')[0];//get the prefix
if (!(key in values))//if we haven't encounter the prefix yet
values[key] = value;//store that the first encounter with the prefix is with 'value'
}
return Object.values(values);//return all the values of the map 'values'
}
较短的版本是这样的:
function removeSimilars(input) {
let values = {};
for (let value of input)
values[value.splitOnLast('-')[0]] ??= value;
return Object.values(values);
}
如果,正如您在评论中提到的,您已经有了可用的前缀列表,那么您所要做的就是迭代这些,以在完整的可能值列表中找到以该前缀开头的每个第一个元素:
const prefixes = ['shape', 'size', 'height']; const list = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'] function reduceTheOptions(list = [], prefixes = [], uniques = []) { prefixes.forEach(prefix => uniques.push( list.find(e => e.startsWith(prefix)) ) ); return uniques; } console.log(reduceTheOptions(list, prefixes));
您可以拆分字符串并获取类型并将其用作对象的 aks 键以及原始字符串作为值。 结果只取对象的值。
const data = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'], result = Object.values(data.reduce((r, s) => { const [type] = s.split('-', 1); r[type] ??= s; return r; }, {})); console.log(result);
尝试这个:
function getRandomSet(arr, ...prefix) { // the final values are load into the array result variable result = []; const randomItem = (array) => array[Math.floor(Math.random() * array.length)]; prefix.forEach((pre) => { const r = arr.filter((par) => String(par).startsWith(pre)); result.push(randomItem(r)); }); return result; } const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']; console.log("Random values: ", getRandomSet(mainArr, "shape", "size", "height"));
我稍微修改了@ofek 的答案。 因为某种原因 ??= 在反应项目中不起作用。
function removeSimilars(input) {
let values = {};
for (let value of input)
if (!values[value.split("-")[0]]) {
values[value.split("-")[0]] = value;
}
return Object.values(values);
}
创建一个新数组并循环遍历第一个数组,如果没有将其推送到新数组,则在每次迭代之前检查元素的存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.