Это экспериментально, но вы также можете поиграть с нативным итератором ES6 (используя генератор) вместо того, чтобы перебирать данные в обратном направлении.
class ClassicIterator {
constructor(list) {
this.list = list;
this.index = 0;
}
*[Symbol.iterator]() {
while (this.index < this.list.length) {
yield this.list[this.index];
this.index++; // Move forward
}
}
remove() {
this.list.splice(this.index, 1);
this.index--; // Rollback
}
}
class InPlaceFilter {
constructor(opts) {
this.list = opts.list;
this.filterFn = opts.filterFn;
}
execute() {
let it = new ClassicIterator(this.list);
for (let item of it) {
if (!this.filterFn(item)) {
it.remove();
}
}
return this;
}
get() {
return this.list;
}
}
const data = [
{ NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true },
{ NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
{ NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
{ NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true }
];
let sameRef = new InPlaceFilter({
list : data,
filterFn : (e) => e[''] === false
}).execute().get();
console.log('Are the same?:', sameRef === data); // Same list!
.as-console-wrapper { top: 0; max-height: 100% !important; }
Упрощенная версия:
const InPlaceFilter = (opts) => {
for (let i = opts.list.length - 1; i >= 0; i--) {
if (!opts.filterFn(opts.list[i])) {
opts.list.splice(i, 1);
}
}
return opts.list;
}
const data = [
{ NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true },
{ NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
{ NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
{ NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true }
];
let otherRef = data.filter(e => e[''] === false);
let sameRef = InPlaceFilter({
list : data,
filterFn : (e) => e[''] === false
});
console.log('Are the same?:', sameRef === data); // Same list!
console.log('Are the same?:', sameRef === otherRef); // Not the same list!
.as-console-wrapper { top: 0; max-height: 100% !important; }