Eliminate items from within the Array object prototype

I am attempting to enhance the functionality of a JavaScript native array within an Angular service without extending global objects through prototyping.

app.factory('Collection', function($http, $q) {
    var Collection = function(arr) {
        this.key = 'id';
        this._last = 0;
        this._first = 77777777; //just big number.
        this.append(arr);
    }
    Collection.prototype = new Array;
    Collection.prototype.orderBy = function(n, reverse) {
        if (reverse) {
            this.sort(function(a, b) {
                return b[n] - a[n];
            })
        } else {
            this.sort(function(a, b) {
                return a[n] - b[n];
            })
        }
    }
    Collection.prototype.spliceBy = function(key, val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i][key] !== val) {
                this.splice(i, 1); ///THIS NEVER HAPPENS !!
                console.log('removed ' + i + ' from ', this);
            }
        }
    }
    Collection.prototype.subset = function(key, val) {
        return this.filter(function(v) {
            return (v[key] === val);
        });
    }
    Collection.prototype.add = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i][this.key] > this._last) {
                this._last = this[i][this.key];
            }
            if (this[i][this.key] < this._first) {
                this._first = this[i][this.key];
            }
            if (this[i][this.key] === data[this.key]) {
                if (override) {
                    this[i] = data;
                    console.log('updated uniquePush');
                }
                return i;
                break;
            }
        }
        var id = this.push(data) - 1;
        data._index = id;
        return id;
    }
    return collection
});

The above code works perfectly except for the spliceBy function. I am trying to filter out elements that do not have a certain value. For instance, in my controller:

.controller(function($scope,Collection){

$scope.posts = new Collection;

$scope.posts.add({id:1,type:'post'});
$scope.posts.add({id:2,type:'comment'});

//Collection is now [{id:1,type:post},{id:2,type:comment}];

//I want to remove all comments from the array
$scope.posts.spliceBy('type','comment');

});

When I call spliceBy, nothing seems to happen :*(

Answer №1

When using the spliceBy function, it may encounter an issue with consecutive elements needing to be removed. This is due to how splice updates indexes within the array length range. A potential solution to this problem involves the following modification:

EnhancedArray.prototype.spliceBy = function(key, val) {
    var i = this.length;
    while (i--) {
        if (this[i][key] !== val) {
            this.splice(i, 1); ///THIS NEVER HAPPENS !!
            console.log('Item at index ' + i + ' has been removed from the array.', this);
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Crafting a smooth curve between a pair of points using Three.js

I am currently working on a Three.js visualization project where I need to connect points using a spline. After adding points to an array and passing it to THREE.SplineCurve3, I am able to render the spline by stepping through the points. However, I encou ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

Differences between referencing and valuing in arrays in JavaScript

I have noticed an interesting behavior when passing arrays to functions by reference. Even after modifying the array inside a function, the changes do not reflect when logging the array outside the function. For example: let arr = [1, 2]; console.log(arr ...

Is it possible for JQuery AJAX requests to activate Angular ng-click directives?

I've been working on a mobile application that uses a combination of JQuery and Angular. Every now and then, I encounter a strange bug. The Angular directives are implemented in a partial that is included through the ng-include directive: <ng-inc ...

Exploring the Solution for Connecting Angular FormArray with mat-select options and input fields

Encountering a situation where the user can open a mat-select and choose an option from the dropdown, triggering the display of a hidden form for filling. Initially, this worked fine with a static template. But now, we have transitioned to linking the mat- ...

Render a specific number of instances of a react component

Below is a code snippet that I am working with: import React, { Component } from 'react'; import {Button} from "@material-ui/core"; import Selector from "./Selector" class Trigger extends Component { constructor(props) { super(props); ...

"Exploring the Power of Angular Service in Combination with Web

I am currently working on optimizing a specific service within my Angular 1 app that performs numerous calculations. My main focus right now is to run this service in a separate thread to enhance the performance of animations. About the App The app revol ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

Issue encountered: The date filter does not seem to be functioning properly when dealing with datetime

When I use the date filter to format my date, it works fine for dates alone. However, when I try to include date and time together, it doesn't work as expected: <tr class='clickable-row' ng-repeat="exam in examlist" ng-click="gotoProfile ...

There was an error: process is not defined / Line 0: Parsing error

When starting a basic Create React App project, I typically begin by running npm install. Next, executing npm start will automatically open the default web browser1. Upon pressing F12, two error messages are displayed in the console. https://i.sstatic.net ...

Encountering difficulties while trying to access the SQLite database file through a JavaScript Axios GET request

Having trouble opening an sqlite DB file from a js axios.get request which is resulting in an exception message being outputted to the console. The request is supposed to call my PHP controller to retrieve data from the DB and return it json-encoded. On t ...

When using the `survey-react` package, there seems to be an issue with the `this.addEvent

Upon inheriting a React project, I am facing difficulty in utilizing the survey-react module. Every time I access http://localhost:3000/, I encounter this error: Uncaught TypeError: this.addEvent is not a function node_modules/survey-react/survey.react.js: ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Encountered an unexpected token '{' error in Discord.js and Node.js integration

let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('Please mention someone to issue ARs.').catch(console.error); mcash[${user.id}, ${message.guild.id}].mc ...

Is there a way to retrieve the value of an HTML form in order to utilize it within a JavaScript function

I am currently working on developing a temperature converter that utilizes a single number input form. When the form is submitted, it should convert the temperature to either Fahrenheit or Celsius. Unfortunately, as a beginner in JavaScript, I have limited ...

Querying GraphQL: Retrieving partial string matches

I have set up a connection to a mongoDB collection using graphQL. Here is the data from the DB: { "_id" : ObjectId("59ee1be762494b1df1dfe30c"), "itemId" : 1, "item" : "texture", "__v" : 0 } { "_id" : ObjectId("59ee1bee62494b1df1dfe30d" ...

Utilize inline scripts within the views of Yii2 for enhanced functionality

I stumbled upon a jQuery code online that allows for the integration of Google Maps, and I'm looking to implement it in my application to ensure accurate address retrieval. You can find the jQuery code here. Currently, I am working with yii2 Advanced ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

Attempting to convert the code from react documentation into class components within a react-create-app, but encountering unexpected behavior

Hey there! I'm currently diving into the world of React and challenging myself by rewriting all the code samples from the documentation in a local react-create-app. However, I've hit a roadblock with this section on the Doc, you can find the code ...

Is it necessary to establish integer variables to keep count while invoking a method?

Here is the scenario: Create a method called occursMoreTimes that determines if the number of occurrences of val1 in an array is greater than the number of occurrences of val2. You can choose to use the findNumberOf method if you see fit. /** *Returns t ...