Make changes to an array in Javascript without altering the original array

I currently have an array :

let originalArr = ['apple', 'plum', 'berry'];

Is there a way to eliminate the item "plum" from this array without altering the originalArr?

One possible solution could be:

let copyArr = [...originalArr];
originalArr = copyArr.filter(item => {
     return item !== 'plum';
});

Answer №1

Instead of creating two extra arrays like copyArr and a filtered array, you can simply create the filtered array. For example:

setOriginalArr(
  originalArr.filter(item => item !== 'plum')
);

This code snippet demonstrates how to filter out 'plum' from the originalArr if it is in the state.

The .filter method does not change the original array but returns a new array. This means you can safely use it in React without the need to clone the original array first.

Answer №2

If you want to fetch specific items from certain indexes without altering the original array, you can utilize the slice() method.

let myArray = ['banana', 'kiwi', 'orange'];
let extracted = myArray.slice(0, 2);
console.log(myArray, extracted)

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

Prevent selection based on JSON information

I am utilizing the Jiren filter library to sort through JSON data. If a particular filter criteria does not match any of the results, I would like to disable that option in the select dropdown. For instance, if "Silversea Expedition" is not found in my re ...

Utilize the JSSOR Slider to dynamically pull images from an online album, such as by integrating with an RSS Feed

My main motivation for exploring this possibility is the negative impact that loading images into the slider has on my website's performance. Is there a method to import images from an externally hosted album, such as Google Picasa albums (or any othe ...

Tips on arranging JSON elements based on the sequence of another JSON

Currently, I am facing a challenge with sorting a list of parks (park_list) based on both distance and area. The code snippet below successfully sorts the list by distance: sortList(index){ return function(a, b){ return (a[index] === b[index] ? 0 : ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Using PHP, JavaScript is unable to hide <div> elements

I'm encountering an issue where the div I want to show when an error occurs is not hiding and showing properly using JavaScript. Here is a snippet of my code: <script> function hideerror() { var catdiv = document.getElementById(error); ...

Attempting to streamline this function in order to avoid running it nine separate times

I have created a day scheduler and successfully saved data in local storage for one hour field. However, I am looking for a way to streamline this function so that I can use it across all 8-hour fields without duplicating the code. Can someone provide me w ...

Achieving checkbox values in Typescript: A guide

I need help with capturing the values of checked checkboxes and storing them in a string to use in my API. I want to retrieve the value if a checkbox is unchecked. <div *ngFor="let x of groupesTable"> <input type="checkbox" [(ngModel)] ...

exploring the digital archives for a specific song file on the computer

Currently in the process of building a website, and I am looking to incorporate a search and filter feature for all music content so that users can play it on my player. Wondering if this is possible? Seeking some assistance and creative ideas to make thi ...

Tips for integrating Twitter sharing functionality in React JS

I am looking for a way to enable users to easily share images from my website on Twitter. Although I tried using the react-share module, it does not provide an option to directly share images. This is the snippet of code I currently have: import { Sh ...

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Tips for simulating focus on a Material-ui TextField with a button press

My web application features a unique method for indirectly filling in text fields. Since there are multiple clicks involved (specifically in a calendar context) and numerous fields to fill, I want to provide users with a visual indication of which field th ...

switching back and forth between the registration and login forms

<script> $(document).ready(function(){ $("#register_link").click(function() { $("#login_or_register").empty(); $("#login_or_register").load("register_form.php"); }); $("#login_link").click(function() { $("# ...

Believing that members possess a certain role when they actually do not

const { Discord, MessageEmbed } = require("discord.js"); module.exports = { name: "ban", description: "bans user from guild", execute(client, message, cmd, args, Discord) { const member = message.mentions.u ...

Evolving fashion trends

I'm looking to dynamically change the style of my HTML element based on screen size, similar to this example: <p [ngStyle]="{'color': isMobile() ? 'red' : 'blue'}">Lorem Ipsum</p> The code above triggers a m ...

Inconsistent Animation Issue with jQuery Toggle for Expanding Div and Text

My expanding div functionality is almost perfect, but I've noticed that the transition when opening abruptly on divs with text. However, the closing transition is smooth. Can anyone help me make the opening transition as smooth as the closing one? Bel ...

Enhance the visual appeal of your checkboxes in React Fluent UI by customizing the color of the checked mark and

I have a React application using Fluent UI. Currently, the <Checkbox/> component is displaying with its default colors and behavior like this: I want to customize the color of the checked mark and label (Green for checked mark and brown for label). ...

What is the best way to retrieve a file using XMLHTTPRequest and Ajax?

I am currently using window.location.href to download a file, but this method requires a second call to my servlet which takes about 1 minute to generate the file. How can I download the file using XMLHTTPRequest instead? The solution should only work wi ...

Set up a JavaScript function that triggers an alert if two numbers are determined to be equal

I created a code snippet that should display an alert message when a button is clicked, indicating whether two random numbers generated are equal or not. The random numbers must be integers between 1 and 6. I implemented this functionality in JavaScript bu ...

"Enhance your website with Ajax code that enables automatic refreshing of a PHP file, keeping its values up-to-date

Before diving in, I want to make it clear that my understanding of ajax is limited. I'm currently working on a small application where I have a load.php file that echoes 3 variables: $loadout[0]; $loadout[1]; $loadout[2]; The PHP file is functioning p ...

Adaptive Container with Images that are not stretched to full width

Is there a way to achieve the same effect as seen in images 2 and 3 here: Although these images already have their own "padding," I'm curious if it can be replicated using just jQuery and CSS? I would appreciate any help or insights on this. Thank y ...