Is there a way to remove array elements once in order to replace them with new ones using a for loop?

My objective is to achieve the following:

  1. Assign an array value (list) to another array (options).
  2. If the user input (searchVal) matches a value in the list, remove existing options and add this match. Subsequently continue adding any additional matches without clearing the options array again.

Based on the code snippet below, if searchVal was "whatever", the expected output for options should be:

["whatever", "whatevEver1"]
. However, the actual result is:
["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]

Snippet of relevant code:

var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
    
    
for (var i=0 ; i < list.length ; i++)
{
    options.push([list[i]]);
}
    
var searchVal = window.prompt(" ");
     
for (var i=0 ; i < list.length ; i++)
{
    if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
        if (clear == 0) {
            options.length = 0; 
        }
        options.push([list[i]]);
    }
    clear++;
}

return options;

Answer №1

When dealing with JavaScript arrays, it's important to remember that they are pass-by-reference. To create a separate copy of an array, you can use the following code snippet:

let newArray = JSON.parse(JSON.stringify(originalArray));

I haven't personally tested this solution on your specific problem as I'm feeling a bit lazy right now, but I believe it should do the trick.

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

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

Passing two variables through a Javascript URL to dynamically update a dropdown menu based on the specified values

What is the best way to send two variables to a JavaScript function in order to modify the dropdown list according to those values? $(document).ready(function() { $("#date").change(function() { $(this).after('<div id="loader">& ...

Tips for choosing a specific value that matches a property value within a JSON dataset

Is there a way to select a specific value in JSON based on another property value? For example, I would like to pass the configuration_code and retrieve the corresponding description. configurations: Array(2) 0: configuration_code: "SPWG" d ...

Basic animation feature malfunctioning

So, I'm really new to this whole HTML5 canvas thing and I'm trying to make a pixel move across the screen with an additive tail behind it. The idea is for the tail to scroll away once it reaches a certain point while the pixel continues moving. I ...

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

Implementing conditional statements using jQuery for multiple selections

Having two unique IDs, I am planning to set a condition that corresponds with my query. $("#foo", "#bar").foo.bar({ baz: function() { if(selector == "#foo") { console.log("foo"); } else { console.log("bar"); } } }); ...

Ensure that the objection model aligns with the TypeScript interface requirements

I am currently working on implementing an API using express, objection.js, and TypeScript. I found a lot of inspiration from this repository: https://github.com/HappyZombies/brackette-alpha/tree/master/server/src Similar to the creator, I aim to have var ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

How to detect the Back Button or Forward Button events in a single-page application

Currently, I am developing a single-page application that utilizes ASP.NET MVC, Backbone.js, and JQuery. My task involves capturing the browser's back and forward button events for breadcrumb implementation. I previously attempted to use the hashchan ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

Update the user information by using its unique identifier at a specific location

I am currently working on editing user data with a specific MongoDB instance. When I click on the user's details, a modal popup appears with an update button below it. My goal is to have the user data updated when this button is clicked for the partic ...

Ensuring Vue.js correctly re-renders an array item

In my vue.js 2 project, I am working with an array that has the following structure: data() { return { ports: [ { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}, { id: 2, ...

Urgent dependency alert: calling for a necessity (sequelize) in next.js is a vital element

I'm encountering a challenge with integrating sequelize into my Next.js 13 project to connect my API routes with the database. I keep receiving errors that say "Critical dependency: the request of a dependency is an expression." import * as pg from &a ...

transforming a cylindrical shape into a curved pipe

Utilizing the capabilities of three.js, I have successfully engineered a captivating scene featuring a textured and meshed cylinder along with a grid boasting lines and vertices. By manipulating the mouse to the left or right, the cylinder elegantly spins ...

I am experiencing difficulty with the Click() operation in Selenium web driver as it is not successfully redirecting me to another page

Hello everyone, I could really use your assistance with a problem I'm facing. WebElement wb=driver.findElement(By.name("NavHeader1$tabs$ctl00$btnNavHeaderTab")); Actions act=new Actions(driver); act.moveToElement(wb).perform(); ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

Is it possible to access a component's function from outside an ng-repeat in Angular 1.5?

Recently delved into learning Angular 1.5 components and testing out some fresh concepts, however, I'm struggling to wrap my head around this particular issue: Here's the code snippet from my Main: angular.module('myapp',[]) .contr ...