Delete element from array using a specific key and value pair

Is it possible to remove objects from an array using a key/value combination? For instance, removing all "non-active" users from the array?

Here is an example of what the code might look like:


var items = [ 
  { "userID":"694", "active": false }, 
  { "userID":"754", "active": true }, 
  { "userID":"755", "active": true },
  { "userID":"760", "active": false },
  { "userID":"761", "active": false },
  { "userID":"762", "active": false }
]

function removeByKey(array, params){
  array.some(function(item, index) {
    return (array[index][params.key] !== params.value) ? !!(array.splice(index, 1)) : false;
  });
  return array;
}

for (var i = 0; i < items.length; i++){ 

var removed = removeByKey(items, {
  key: 'active',
  value: true
});
}

console.log(removed);
        

However, there seems to be an issue when the last entry in the array has "active": false. It doesn't get removed as expected.

If you have any solutions or suggestions, please feel free to share!

Answer №1

Perhaps using a function similar to this:

function filterByParameter(arr, criteria) {
  return arr.filter(item => item[criteria.key] !== criteria.value)
}

Answer №2

Removing an element, such as the second to last one, in a loop may cause the next element to be skipped due to index changes. To maintain functionality with a custom remover function, you can use the following approach:

let previous;
do {
    previous = items.length;
    removeByKey(items, {
      key: 'active',
      value: true
    });
 } while(previous !== items.length)

However, this method is inefficient. It is recommended to update the removal method to eliminate all occurrences rather than just the first one found (using forEach instead of some, or simply utilizing filter).

Answer №3

Items that meet the specified condition are stored in a variable called filteredItems.

Answer №4

Here is an alternative approach to @Jayfee's solution in ES5:

function filterByProperty(arr, propVal) {
  return arr.filter(function(item) {
    return item[propVal.key] !== propVal.value;
  });
}

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

What is the best way to handle input data as variables?

I'm looking to learn how to input data in HTML using elements like <input> and then utilize that data. Specifically, I'm interested in entering someone's age and being able to use it as a variable to create functions related to age in ...

Use React-table to store the value of an accessor in the state while also utilizing a

I am currently working on implementing a checkbox table using react-table. The primary objective is to have checkboxes in the first column, and upon selection of a checkbox, I intend to store the ID defined in the accessor in the state. Despite going thro ...

A step-by-step guide on transforming an array of objects into an array of arrays with the help of Ramda

I want to convert the following data: [ { a: 2000, b: 4000 }, { a: 8000, b: 5000 }, { a: 6000, b: 1000 } ]; Into this format: [ [ 2000, 8000, 6000 ], [ 4000, 5000, 1000 ] ]; Using Ramda library. I am able to achieve this using R.reduce functio ...

Loop through to display response information

After submitting data using jQuery's .ajax() method, I receive a response back with some information that needs to be displayed on my webpage. For instance, this is an example of the response: { "res": 1, "item": [ {"id":"1","desc":"blue ...

Retrieve the value associated with the key 'Name' using jq

When using jq to extract a key value, I only want to retrieve it if the key name is Name. For instance, I have some AMI's that do not have a key name of Name and I want to skip over those. Here's an example: aws ec2 describe-snapshots --snapshot ...

Prevent unchecking a checked list item by clicking on it

Is it possible to prevent the user from unchecking a list item once it has been checked? Your assistance is greatly appreciated! $(".collectioncontainer ul li").click(function(){ $('.collectioncontainer ul li.checked').not(this).removeClass( ...

What is the best way to create a function that requires an argument in TypeScript?

I'm looking to bring in a module that requires an argument in Typescript. This is how it looks in javascript: const cors = require('cors')({origin: true}); // JS What would be the equivalent syntax in Typescript? ...

Converting strings into arrays and then displaying them in the C programming language

I am currently working on a program that takes user input as a string and searches for specific codes within another set of strings. The goal is to add the alphabetic representation of each code found into an array, which will eventually be displayed if al ...

Obtaining the Ultimate Redirected URL in PowerShell

I've been searching for similar solutions, but haven't found exactly what I need. Here's the situation: I'm working on a PowerShell script to extract information from Chrome and Microsoft Edge (chromium-based) extensions directories. M ...

Convert an ansible list of dictionaries into JSON with a modified structure

I'm struggling with transforming a list of dictionaries into the required JSON structure to be sent as a variable to another module. Initially, I have a list of dictionaries that provides information about the 'teams' being created in awx/T ...

What is the best way to incorporate data from my Input field into my Vue.JS application's existing data structure

Struggling with integrating new users into my personal project, particularly in passing input values (userName and userAge) to the parent element for addition to playersData. Here is a sample code snippet from the child component: `<template> <d ...

What is the method to have the console display false when the phrases are not in the correct sequence? Node.js

The existing code currently outputs true when message == 'john hi', but I require it to output false when the words are not in the correct order. In this scenario, elements from array1 should precede elements from array2. Additionally, I should ...

iOS - Embedding text into a UIWebView input field

Just a quick question - if a textfield in a webform does not automatically have the focus set by the form, meaning you have to press the field before the keyboard pops up, am I correct in assuming that the field cannot be edited? In simpler terms - is it ...

Vue.JS component containing DOM elements outside of the designated $el scope

Transitioning from a custom front-end framework to Vue is a new adventure for me. Our website is gradually integrating Vue, and as we refactor old components, I've encountered an issue. My question is: Can a component create DOM elements outside of i ...

Assess the scss styles specific to components following the global min.css in a React application

ISSUE Imagine we have a min.css file that needs to be imported globally: index.js import ReactDOM from "react-dom"; import App from "src/App"; import "library/library.min.css"; ReactDOM.render(<App />, document.getE ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

How to use jQuery to update the href attribute of a parent link

Can someone help me figure out why I am having trouble changing the 'href' of the parent link to a header logo? Thank you in advance! Here is the HTML code snippet: <a href="https://URL.IWANTO.CHANGE"> <img id="partner_logo" src="/ ...

Dynamic tables are experiencing issues with Javascript functionality

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content- ...

Troubleshooting: Issue with passing variables from jQuery $.ajax to PHP

I am working on creating a 'show more' button using jQuery AJAX. The button has a loaded attribute like this: <button type="button" class="smbt btn center-block" data-loaded="3">Show More</button> In my JavaScript file, I have the f ...

PreventDefault() equivalent: Proceeding with ActionLink function logic

<%: Html.ActionLink("Print", "Print", "Print", New With {.id = Model.ID}, New With {.target = "_blank", .class = "print"})%> Is there a way to ensure that the _blank page opens even after using preventDefault in the click event? $('#NameOfB ...