How to Update Values Inside an Array

share link

by Abdul Rawoof A R dot icon Updated: Mar 28, 2023

technology logo
technology logo

Solution Kit Solution Kit  

To update values in a JavaScript array, we can use the findIndex() method for executing and updating the object values accordingly, using for loop method for iterating through an array and updating the specified value. Map() for mapping the updated value to an array in JavaScript.


Update new values in an array,

  • First, find the element that we want to find the index in the array of the object or where the object is in the array.
  • Then create a copy of the state array.
  • Update or add one value.
  • Finally setState.


Use the setState() function whenever we want to update the values in the state. Then, the component gets rendered again automatically without our knowledge. We'll want to pass a new array to our state-setting function to update an array every time. To implement that, we can create a new array from the original array in our state by calling its non-mutating methods like filter() & map(). Then we can set our state to the resulting new array. The difference between the setState and replaceState is that the setState will merge the current and previous states. Whereas replaceState will throw out the current state and replaces it with only what we feed.


Here is an example of how you can Update the values inside an Array in JavaScript:

Fig : Preview of the output that you will get on running this code from your IDE.

Code

In this solution we're using React library.

import React, { Component, Fragment } from "react";

export default class App extends Component {
  state = {
    items: [
      { id: "Apples", quantity: 0 },
      { id: "Strawberries", quantity: 0 },
      { id: "Grapes", quantity: 0 },
      { id: "Apricots", quantity: 0 }
    ]
  };

  handleChange = ({ target: { id, value } }) => {
    this.setState(prevState => ({
      items: prevState.items.map(item => {
        const nextVal = item.quantity + ~~value; // ~~ === parseInt(val, 10) -- required because the "value" is turned into a string when placed on a DOM element

        return id === item.id
          ? { id, quantity: nextVal > 0 ? nextVal : 0 }
          : { ...item };
      })
    }));
  };

  render = () => (
    <div className="container">
      <h1>Updating Values Inside Array</h1>
      {this.state.items.map(({ id, quantity }) => (
        <div key={id} className="container">
          <div>
            {id} ({quantity})
          </div>
          <button
            id={id}
            value={1}
            style={{ marginRight: 10 }}
            className="uk-button uk-button-primary"
            onClick={this.handleChange}
          >
            +
          </button>
          <button
            id={id}
            value={-1}
            style={{ marginRight: 10 }}
            className="uk-button uk-button-danger"
            onClick={this.handleChange}
          >
            -
          </button>
        </div>
      ))}
    </div>
  );
}

import React, { Component, Fragment } from "react";
import Button from "./button";

export default class App extends Component {
  state = {
    items: [
      { id: "Apples", quantity: 0 },
      { id: "Strawberries", quantity: 0 },
      { id: "Grapes", quantity: 0 },
      { id: "Apricots", quantity: 0 }
    ]
  };

  handleChange = (id, val) => {
    this.setState(prevState => ({
      items: prevState.items.map(item => {
        const nextVal = item.quantity + val;

        return id === item.id
          ? { id, quantity: nextVal > 0 ? nextVal : 0 }
          : { ...item };
      })
    }));
  };

  render = () => (
    <div className="container">
      <h1>Updating Values Inside Array</h1>
      {this.state.items.map(props => (
        <div key={props.id} className="container">
          <div>
            {props.id} ({props.quantity})
          </div>
          <Button
            {...props}
            className="uk-button uk-button-primary"
            handleChange={this.handleChange}
            value={1}
          >
            +
          </Button>
          <Button
            {...props}
            disabled={props.quantity === 0}
            className="uk-button uk-button-danger"
            handleChange={this.handleChange}
            value={-1}
          >
            -
          </Button>
        </div>
      ))}
    </div>
  );
}

import React, { PureComponent } from "react";
import PropTypes from "prop-types";

export default class Button extends PureComponent {
  static propTypes = {
    children: PropTypes.string.isRequired,
    className: PropTypes.string,
    disabled: PropTypes.bool,
    id: PropTypes.string.isRequired,
    handleChange: PropTypes.func.isRequired,
    value: PropTypes.number.isRequired
  };

  handleClick = () => {
    this.props.handleChange(this.props.id, this.props.value);
  };

  render = () => (
    <button
      disabled={this.props.disabled || false}
      className={this.props.className}
      onClick={this.handleClick}
      style={{ marginRight: 10 }}
    >
      {this.props.children}
    </button>
  );
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Install npm i uikit and import this library in index.js as import "uikit/dist/css/uikit.min.css".
  5. Open the folder in IDE.
  6. Copy the code using "copy" button above then create a file in the name of UpdateQuantity.js and paste it in that UpdateQuantity.js file(Use only first 55 lines of code).
  7. Import UpdateQuantity.js file in index,js file(also refer demo given below).
  8. Create a style file(eg: styles.css) and get the code for style file from 'DEMO' given below and import it in index.js file.
  9. Open the terminal from IDE.
  10. npm start to run the file.


Note: In index.js file, inside <React.StrictMode> tag replace '<App>' with '<UpdateQuantity>'.


You can also refer this url 'DEMO' for getting the above output.

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for 'react interview exercise' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Visual Studio Code 1.73.1.
  2. The solution is tested on node v18.12.1 and npm v8.19.2.
  3. React version-18.2.0.
  4. Uikit version-current.


Using this solution, we are able to update values inside an array in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to update values inside an array in React.

Dependent Libraries

reactby facebook

JavaScript doticonstar image 209050 doticonVersion:v18.2.0doticon
License: Permissive (MIT)

The library for web and native user interfaces

Support
    Quality
      Security
        License
          Reuse

            reactby facebook

            JavaScript doticon star image 209050 doticonVersion:v18.2.0doticon License: Permissive (MIT)

            The library for web and native user interfaces
            Support
              Quality
                Security
                  License
                    Reuse

                      uikitby visionmedia

                      JavaScript doticonstar image 1321 doticonVersion:Currentdoticon
                      License: Others (Non-SPDX)

                      UIKit - modern ui components for the modern web

                      Support
                        Quality
                          Security
                            License
                              Reuse

                                uikitby visionmedia

                                JavaScript doticon star image 1321 doticonVersion:Currentdoticon License: Others (Non-SPDX)

                                UIKit - modern ui components for the modern web
                                Support
                                  Quality
                                    Security
                                      License
                                        Reuse

                                          You can also search for any dependent libraries on kandi like 'react' and 'uikit'.

                                          Support

                                          1. For any support on kandi solution kits, please use the chat
                                          2. For further learning resources, visit the Open Weaver Community learning page.


                                          See similar Kits and Libraries