我有两个数组,一个数组包含价格,另一个数组包含日期。我想删除所有重复的价格,我想删除日期数组的相同索引。怎么做呢?
我的数组的一个例子:['2022-06-27', '2022-07-02', '2022-07-03', '2022-07-04', '2022-07-05']
[3.79, 4.29, 4.29, 4.29, 4.36]
需要的最终结果:
['2022-06-27', '2022-07-02', '2022-07-05']
[3.79, 4.29, 4.36]
一个for
循环,将使用arr.lastIndexOf(item)找到的所有重复项拼接在一起。
var arr2 = ['2022-06-27', '2022-07-02', '2022-07-03', '2022-07-04', '2022-07-05'];
var arr1 = [3.79, 4.29, 4.29, 4.29, 4.36];
for (var i = 0; i < arr1.length; i++) {
var current = arr1[i];
var lastIndex = arr1.lastIndexOf(current);
while (lastIndex > i) {
arr1.splice(lastIndex, 1);
arr2.splice(lastIndex, 1);
lastIndex = arr1.lastIndexOf(current);
}
}
console.log(arr1)
console.log(arr2)
您可以将价格作为键的哈希表的值作为过滤索引。然后将日期和价格作为结果。
const
dates = ['2022-06-27', '2022-07-02', '2022-07-03', '2022-07-04', '2022-07-05'],
prices = [3.79, 4.29, 4.29, 4.29, 4.36],
indices = Object
.values(prices.reduce((r, p, i) => (r[p] ??= i, r), {}))
.sort((a, b) => a - b),
datesNew = indices.map(i => dates[i]),
pricesNew = indices.map(i => prices[i]);
console.log(...datesNew);
console.log(...pricesNew);
您可以尝试以下方法:
const dates = ['2022-06-27', '2022-07-02', '2022-07-03', '2022-07-04', '2022-07-05']
const arr = [3.79, 4.29, 4.29, 4.29, 4.36];
const arrSet = new Set(arr);
const relatedDates = [...arrSet].map((value) => dates[arr.indexOf(value)]);
console.log([...arrSet]);
console.log(relatedDates);
输出:[3.79, 4.29, 4.36]
['2022-06-27', '2022-07-02', '2022-07-05']