I have 2 arrays, one array contains prices and the other one dates. I want to remove all duplicate prices , and I want to remove the same indexes of the date array. How would one do this?
An example of my arrays:
['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]
end result needed:
['2022-06-27', '2022-07-02', '2022-07-05']
[3.79, 4.29, 4.36]
CodePudding user response:
A for
loop, splicing along the way all the duplicates found using 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)
CodePudding user response:
You can try this approach:
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);
Output:
[3.79, 4.29, 4.36]
['2022-06-27', '2022-07-02', '2022-07-05']
CodePudding user response:
You could take the values of a hash table with prices as keys as filtered indices. Then map dates and prices as result.
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), {})),
datesNew = indices.map(i => dates[i]),
pricesNew = indices.map(i => prices[i]);
console.log(...datesNew);
console.log(...pricesNew);