Issue
I have an array that I need to create which I do by doing an forEach() on 2 levels to get the data. I tried to filter it the basic way but with no succes, is it cause of the ø caracter ? :
const ascending: any= values.sort((a,b) => (a > b ? 1 : -1));
Here’s my code and the array :
Array I’m trying to filter
Full array that I forEach on :
Filter methode : ( dataDynParts being the second picture )
filterDrop() {
const newArr = [];
const secondArr = [];
this.dataDynParts.forEach((item) => {
item.items.forEach((val) => {
val.diam.forEach((rez, index) => {
console.log(index)
if (newArr.findIndex(i => i === rez) === -1) {
if (index === 0) {
newArr.push(rez);
}}
if (secondArr.findIndex(i => i === rez) === -1) {
if (index === 1) {
secondArr.push(rez);
}
}
});
});
});
console.log(secondArr);
this.dataDiam1 = newArr;
this.dataDiam2 = secondArr;
this.filteredWithDiam = this.dataDynParts;
}
Solution
It does seem to work correctly – more or less. You’re trying to sort diameters, which in reality are numbers. But you’re sorting strings, so i.e. "100" will come before "25" (since 1 is before 2).
To have it work properly, you’ll need to parse your values to numbers and then compare them. Let’s assume that they all have initial character of ø.
Something like this should do the trick:
values.sort((a: string, b: string) => {
// Remove the first character and replace . with , to prepare for parsing
const aVal = a.substr(1).replace('.', ',');
const bVal = b.substr(1).replace('.', ',');
// Parse to numbers
const aNum = parseFloat(aVal, 10);
const bNum = parseFloat(bVal, 10);
// Compare values
return aNum - bNum;
});
Below is non-typescript version for the stack overflow snippet testing:
var values = ['ø63', 'ø22'];
var values2 = ['ø50', 'ø25', 'ø40', 'ø16,5', 'ø100', 'ø165'];
var sort = (values) => values.sort((a, b) => {
// Remove the first character and replace . with , to prepare for parsing
const aVal = a.substr(1).replace('.', ',');
const bVal = b.substr(1).replace('.', ',');
// Parse to numbers
const aNum = parseFloat(aVal, 10);
const bNum = parseFloat(bVal, 10);
// Compare values
return aNum - bNum;
});
console.log(sort(values));
console.log(sort(values2));