Eliminate an item from an array that contains multiple arrays

I am working with a multidimensional array that looks like this:

myArray = [
  ["ooooh", "that"],
  ["dog ", "of"],
  ["mine", "word...."]
]

My goal is to remove the array item: ["ooooh", "that"]

Although I know that element 0 is "ooooh" and element 1 is "that", I do not know the position of these elements within the larger array. Is there an efficient way to achieve this?

After researching, I found suggestions like delete myArray['1'] or knowing the index of the element in the array - but in my case, I need both elements 0 and 1 to match for removal.

In pseudo code, I would like to do something like:

myArray.destroy(["ooooh", "that"])

Any ideas on how to make this happen?

Answer №1

If you want to take an item out of a list, you can utilize the splice method.

myList.splice(
   myList.findIndex( item => 
     item[0] == "ooooh" && item[1] == "that"
   ), 
1);

I hope this explanation is helpful :>

myList = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word...."]];

myList.splice(myList.findIndex(item => item[0] == "ooooh" && item[1] == "that"), 1);

console.log(myList)

Answer №2

Just apply a filter to your array

var myList = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word...."]
]

deleteFromList = (val, list) => list.filter(a=>JSON.stringify(a)!=JSON.stringify(val))

console.log(
  deleteFromList(["ooooh", "that"], myList)
)

/* Alternatively */

myList = myList.filter(a=>JSON.stringify(a)!=JSON.stringify(["ooooh", "that"]))

console.log(myList)

Answer №3

Combining the filter and every functions allows for a flexible approach.

const wordsList = [
  ["apple", "banana"],
  ["cat", "dog"],
  ["elephant", "flower"]
];

const wordsToRemove = ["apple", "banana"];

const result = wordsList.filter(word => !wordsToRemove.every(item => word.includes(item)));
console.log(result);

Answer №4

There are various methods to achieve this, as mentioned in the previous responses. However, I find that using the filter function is the most straightforward approach. Here is an example:

myList = [
    ["ooooh", "that"],
    ["dog ", "of"],
    ["mine", "word"]
];
    
myList = myList.filter((element) =>
    //filter condition 
    (!
       ((element[0] == 'ooooh') && (element[1] == 'that'))
    )
);

console.log(myList)

Answer №5

If you want to compare arrays as strings, you can utilize the filter function.

myList = [
  ["ooooh", "that"],
  ["dog ", "of"],
  ["mine", "word...."]
];

let findMe = ["ooooh", "that"]

myList = myList.filter((curr) => curr.join() !== findMe.join())

console.log(myList)

Answer №6

I may be a little late to the gathering, but I have some thoughts to share:


let items = [
  ["oh wow", "this"],
  ["cat", "is"],
  ["crazy", "cool"]
];

Array.prototype.remove = function(array) {
  this.forEach((element, index) => {
    if (JSON.stringify(element) === JSON.stringify(array)) {
      this.splice(index, 1);
    }
  });
}

console.log(items);

items.remove(["oh wow", "this"]);

console.log(items);

Answer №7

You have the option to utilize the pop method to eliminate an element from your array.
This link leads to its documentation.

myArray = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word..."]
]

console.log("Initial Array:");
console.log(myArray);

/**
 * Deletes a specific array from an array of arrays 
 *
 * @param  {String} myArray       - The original array of arrays
 * @param  {String} arrayToRemove - The array that will be deleted from myArray
 */
function destroy(myArray, arrayToRemove) {
        arrayIndexToBeRemoved = myArray.findIndex(item => item[0] == arrayToRemove[0] && item[1] == arrayToRemove[1]);
        if (arrayIndexToBeRemoved != -1){
            removedArray = myArray.pop(arrayIndexToBeRemoved);
            console.log("Deleted: " + removedArray);
        } else {
            console.log("Unable to locate: " + arrayToRemove + " in: " + myArray);
        }
}

destroy(myArray, ["mine", "word..."]);

console.log("Updated Array:");
console.log(myArray);

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

Create a new Chart.js Chart by using the data retrieved from an AJAX request and encoded in JSON

I am currently working on drawing a chart using the chart.js library. The initial draw works perfectly fine, but I am facing issues when trying to redraw the doughnut chart with new data retrieved from an ajax call. My approach involves PHP and Codeignite ...

Utilize Vue in external files

One way I would like to improve readability in my project is by defining routes in an external file. The starting point for my Vue app is the main.js file, where I initialize everything. Take a look: import Vue from 'vue' import VueRouter from ...

How can I access the target element during ng-change event?

I am using an ng-repeat to display multiple textareas, and I need to be able to access the target element when the ng-change event is triggered. <div ng-repeat="item in $ctrl.items"> <textarea ng-change="$ctrl.changed()"></textarea> &l ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

Enhancing JavaScript Arrays by incorporating data from a JSON file

Could you kindly advise me on what I might be doing incorrectly here? It seems like a simple issue, but it has taken up the entire day. All I wanted to do was add a value to an array called messages from a JSON file. function get_message(params) { va ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

I am unsure of the timestamp format for the value 1522899000000. Can it be used in both Ionic and AngularJS? And how would one go

While parsing a JSON from an external URL, I came across a timestamp with the value starttime: 1522899000000 (on 4/5/2018 -> 5th April 2018). The value seemed like a Unix timestamp, but when I tried to convert it, it displayed the year 1912. What kind o ...

Style the div element with CSS

Is there a way to style a div element within an HTML document using Sencha framework? I have specific CSS properties that I would like to apply to my div. #logo{ position:absolute; top:20%; left:0%; } Below is a snippet of my Sencha code: Ex ...

Is there a way to show a pre-set username value to prevent receiving an error message that says it's undefined?

My navigation bar is set up to show the following on the right side of the screen: Welcome, <%= user %> The issue is that I can only access the user data if I render it in the following way: router.get("/", function (req, res, next) { co ...

Looping through an array and appending distinct elements to a fresh array

I am currently facing an issue and seeking feedback on how to resolve it. Below is the JSON data: questions: [ { question: 'lala', answer: 'papa', categories: ['Handla'] }, { question: ...

What is the best way to determine the nearest pixel point indexes of an RGB list compared to another RGB list?

I have been working on an Image Processing Task and I have outlined all the details below. What I aim to accomplish: In this task, I am dealing with two lists: colorlist = approximately 500 RGB values (extracted from Picture 1) color = around 1200 or m ...

Upload your existing image files to Dropzone

I have implemented image upload functionality using Dropzonejs in a form. To handle multiple form fields, I have set autoProcessQueue to false and processing it on click of the Submit button as shown below. Dropzone.options.portfolioForm = { url: "/ ...

Tips on utilizing browser.getCurrentUrl() within a Protractor examination

I’ve been wrestling with these lines of Protractor code today: element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ... It seems that getCurrentUrl always throws an error when placed after a waitF ...

Error in array presentation due to structural issues

Can someone explain why adding the member Node_ptr next; to the structure causes the elements in the array poly[1] and poly[2] to display incorrect values? Interestingly, omitting Node_ptr next; allows the correct values to be displayed for indexes 1 and 2 ...

Utilize DTOptionsBuilder and AngularJs ColVis to trigger actions when there are changes in column visibility

In my AngularJs project, I am using DTOptionsBuilder with ColVis plugin to show and hide columns in a datatable. I need to perform certain operations when the visibility of the columns changes. I came across an event called 'column-visibility.dt' ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Monitoring changes in an array of objects using AngularJS's $watch function

Exploring the world of AngularJS, I'm on a quest to solve a challenging issue efficiently. Imagine having an array of objects like this: var list = [ {listprice: 100, salesprice:100, discount:0}, {listprice: 200, salesprice:200, discount:0}, {listpr ...

Encountered an issue retrieving tweets from the Twitter API 1.1

I recently completed an online tutorial from this site: However, I'm encountering an error message that simply says 'error: ' without any additional information. To start, here is my PHP script used to fetch the JSON output: <?php sess ...

Ways to correctly import various CSS files for individual routes in a Vuejs application

Currently, I am in the process of developing a project using Vue.js and Laravel. This project will have distinct layouts for the admin/user panel and landing page, requiring different CSS files to be loaded for each route. At the moment, I am utilizing va ...

What is the best way to ensure that the HTML page is only shown once all data from three JSON files has been fully

I have successfully parsed data from three different JSON files using the code below. //factory app.factory('myapp', ['$http', function($http) { function getLists() { var tab = [&a ...