I have a simple question that has been puzzling me. When attempting to reassign an element of an array of objects to another object that meets specific criteria, I noticed that nothing happens. However, if I first set the element to null and then reassign it, the operation works successfully. Below is the list of objects being used:
servers = [
{
instanceType: 'medium',
name: 'Production',
status: 'stable',
started: new Date(15, 1, 2017)
},
{
instanceType: 'large',
name: 'User Database',
status: 'stable',
started: new Date(15, 1, 2017)
},
{
instanceType: 'small',
name: 'Development Server',
status: 'offline',
started: new Date(15, 1, 2017)
},
{
instanceType: 'small',
name: 'Testing Environment Server',
status: 'stable',
started: new Date(15, 1, 2017)
}
];
Here is the method that does not yield results:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(value: any, args?: any): any {
for (const i of value) {
for (const j of value.slice(value.indexOf(i) + 1)) {
if (i.name > j.name) {
value[value.indexOf(i)] = j;
value[value.indexOf(j)] = i;
}
}
}
return value;
}
}
And here is the working method:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(value: any, args?: any): any {
for (const i of value) {
for (const j of value.slice(value.indexOf(i) + 1)) {
if (i.name > j.name) {
const index1 = value.indexOf(i);
const index2 = value.indexOf(j);
value[index1] = null;
value[index2] = null;
value[index1] = j;
value[index2] = i;
}
}
}
return value;
}
}
It's not a critical issue, but I am now curious about why one method fails while the other succeeds. Thank you for your time!
EDIT 1: Modified (i.name[0] > j.name[0]) to (i.name > j.name) for consistency. Both checks produced identical outcomes.