所以我想從陣列中找到唯一值。所以例如我有這個陣列:
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"]
我只想要任何一組不同值中的第一個值。
uj5u.com熱心網友回復:
最簡單的解決方案是迭代串列并將您得到的內容存盤在字典中
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);
}
uj5u.com熱心網友回復:
您可以拆分字串并獲取型別并將其用作物件的 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);
uj5u.com熱心網友回復:
如果,正如您在評論中提到的,您已經有了可用的前綴串列,那么您所要做的就是迭代這些,以在完整的可能值串列中找到以該前綴開頭的每個第一個元素:
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));
uj5u.com熱心網友回復:
嘗試這個:
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) => {
result.push(randomItem(arr.filter((par) => String(par).startsWith(pre))));
});
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"));
uj5u.com熱心網友回復:
創建一個新陣列并回圈遍歷第一個陣列,如果沒有將其推送到新陣列,則在每次迭代之前檢查元素的存在
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/333485.html
標籤:javascript 数组 反应
