removing an element from array not workingHow do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How to append something to an array?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?How do I return the response from an asynchronous call?

Travelling in US for more than 90 days

Calculate Pi using Monte Carlo

Pre-Employment Background Check With Consent For Future Checks

Mac Mini (2018) 10Gb Port Compatibility

Started in 1987 vs. Starting in 1987

How would a solely written language work mechanically

"Marked down as someone wanting to sell shares." What does that mean?

A seasonal riddle

Did I make a mistake by ccing email to boss to others?

Would this string work as string?

Not hide and seek

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

Make a Bowl of Alphabet Soup

Why doesn't Gödel's incompleteness theorem apply to false statements?

Capacitor electron flow

python displays `n` instead of breaking a line

Center page as a whole without centering each element individually

Error in master's thesis, I do not know what to do

Are hand made posters acceptable in Academia?

What is the purpose of using a decision tree?

What is the meaning of "You've never met a graph you didn't like?"

What is the period/term used describe Giuseppe Arcimboldo's style of painting?

Why didn’t Eve recognize the little cockroach as a living organism?

Has the laser at Magurele, Romania reached the tenth of the Sun power?



removing an element from array not working


How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How to append something to an array?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?How do I return the response from an asynchronous call?













0















I'm trying an element from an array using the id of the element yet not successful.



constructor(props)
super(props)
this.state =

arr : [<Input id="1" />,<Input id="2" />,<Input id="3" />,<Input id="4" />],
id: 5




addToArray()
let id = this.state.id
let arr = this.state.arr
let tmp = <Input id=id />
id = id + 1
arr.push(tmp)
this.setState(arr,id)




removeFromArray()

let idx = prompt("Enter index")

let data = [...this.state.arr]
let arr_two = []

arr_two = data.filter(function( element )
return (element.props.id !== idx );
);

this.setState(arr: arr_two)




render(

return()

<Button onClick=() => this. addToArray()>add to array</Button>
<Button onClick=() => this.removeFromArray()>remove from array</Button>


)


no matter what value the user enters, only the last element is being removed. Let say the user inputs 2, the element with the id 4 is gets removed instead of 2 although it exists in the array. How should I modify to resolve the issue










share|improve this question
























  • Please attempt to format your code properly. People who would love to help you will turn away since it's hard to read your code.

    – Aniket G
    Mar 7 at 0:57











  • Can you provide some more code? Like how you render these <Input >?

    – bird
    Mar 7 at 2:26















0















I'm trying an element from an array using the id of the element yet not successful.



constructor(props)
super(props)
this.state =

arr : [<Input id="1" />,<Input id="2" />,<Input id="3" />,<Input id="4" />],
id: 5




addToArray()
let id = this.state.id
let arr = this.state.arr
let tmp = <Input id=id />
id = id + 1
arr.push(tmp)
this.setState(arr,id)




removeFromArray()

let idx = prompt("Enter index")

let data = [...this.state.arr]
let arr_two = []

arr_two = data.filter(function( element )
return (element.props.id !== idx );
);

this.setState(arr: arr_two)




render(

return()

<Button onClick=() => this. addToArray()>add to array</Button>
<Button onClick=() => this.removeFromArray()>remove from array</Button>


)


no matter what value the user enters, only the last element is being removed. Let say the user inputs 2, the element with the id 4 is gets removed instead of 2 although it exists in the array. How should I modify to resolve the issue










share|improve this question
























  • Please attempt to format your code properly. People who would love to help you will turn away since it's hard to read your code.

    – Aniket G
    Mar 7 at 0:57











  • Can you provide some more code? Like how you render these <Input >?

    – bird
    Mar 7 at 2:26













0












0








0








I'm trying an element from an array using the id of the element yet not successful.



constructor(props)
super(props)
this.state =

arr : [<Input id="1" />,<Input id="2" />,<Input id="3" />,<Input id="4" />],
id: 5




addToArray()
let id = this.state.id
let arr = this.state.arr
let tmp = <Input id=id />
id = id + 1
arr.push(tmp)
this.setState(arr,id)




removeFromArray()

let idx = prompt("Enter index")

let data = [...this.state.arr]
let arr_two = []

arr_two = data.filter(function( element )
return (element.props.id !== idx );
);

this.setState(arr: arr_two)




render(

return()

<Button onClick=() => this. addToArray()>add to array</Button>
<Button onClick=() => this.removeFromArray()>remove from array</Button>


)


no matter what value the user enters, only the last element is being removed. Let say the user inputs 2, the element with the id 4 is gets removed instead of 2 although it exists in the array. How should I modify to resolve the issue










share|improve this question
















I'm trying an element from an array using the id of the element yet not successful.



constructor(props)
super(props)
this.state =

arr : [<Input id="1" />,<Input id="2" />,<Input id="3" />,<Input id="4" />],
id: 5




addToArray()
let id = this.state.id
let arr = this.state.arr
let tmp = <Input id=id />
id = id + 1
arr.push(tmp)
this.setState(arr,id)




removeFromArray()

let idx = prompt("Enter index")

let data = [...this.state.arr]
let arr_two = []

arr_two = data.filter(function( element )
return (element.props.id !== idx );
);

this.setState(arr: arr_two)




render(

return()

<Button onClick=() => this. addToArray()>add to array</Button>
<Button onClick=() => this.removeFromArray()>remove from array</Button>


)


no matter what value the user enters, only the last element is being removed. Let say the user inputs 2, the element with the id 4 is gets removed instead of 2 although it exists in the array. How should I modify to resolve the issue







javascript reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 0:58







toy moy

















asked Mar 7 at 0:56









toy moytoy moy

1778




1778












  • Please attempt to format your code properly. People who would love to help you will turn away since it's hard to read your code.

    – Aniket G
    Mar 7 at 0:57











  • Can you provide some more code? Like how you render these <Input >?

    – bird
    Mar 7 at 2:26

















  • Please attempt to format your code properly. People who would love to help you will turn away since it's hard to read your code.

    – Aniket G
    Mar 7 at 0:57











  • Can you provide some more code? Like how you render these <Input >?

    – bird
    Mar 7 at 2:26
















Please attempt to format your code properly. People who would love to help you will turn away since it's hard to read your code.

– Aniket G
Mar 7 at 0:57





Please attempt to format your code properly. People who would love to help you will turn away since it's hard to read your code.

– Aniket G
Mar 7 at 0:57













Can you provide some more code? Like how you render these <Input >?

– bird
Mar 7 at 2:26





Can you provide some more code? Like how you render these <Input >?

– bird
Mar 7 at 2:26












1 Answer
1






active

oldest

votes


















1














You have a number of syntax errors in your original code, and you're not following best practices (e.g. if you're referencing state when using setState, use the callback because setState is asynchronous), but I think the primary issue you were having is that you're comparing strings to numbers.



I refactored your code to use more current methods (i.e. ES6) and added parseInt to convert the input from window.prompt into a number that can be compared to your <Input /> component’s id prop. I also switched the explicit <Input /> declarations to use a numeric input, rather than a string.



Hit run and you'll see that it works as-is.






const Input = ( id ) => <div>id</div>

class Foo extends React.Component
state =
arr: [
<Input id=1 />,
<Input id=2 />,
<Input id=3 />,
<Input id=4 />,
],
id: 5,


addToArray = () =>
const arr = [...this.state.arr, <Input id=this.state.id />]
this.setState(prevState => ( arr, id: prevState.id + 1 ))


removeFromArray = () =>
const id = parseInt(window.prompt("Enter index"))

this.setState(prevState => (
arr: prevState.arr.filter(element => element.props.id !== id),
))


render()
return (
<div>
<div>
<button onClick=this.addToArray>Add to array</button>
</div>
<div>
<button onClick=this.removeFromArray>Remove from array</button>
</div>
Array: this.state.arr
</div>
)



ReactDOM.render(<Foo />, document.getElementById("root"))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>








share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55034472%2fremoving-an-element-from-array-not-working%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You have a number of syntax errors in your original code, and you're not following best practices (e.g. if you're referencing state when using setState, use the callback because setState is asynchronous), but I think the primary issue you were having is that you're comparing strings to numbers.



    I refactored your code to use more current methods (i.e. ES6) and added parseInt to convert the input from window.prompt into a number that can be compared to your <Input /> component’s id prop. I also switched the explicit <Input /> declarations to use a numeric input, rather than a string.



    Hit run and you'll see that it works as-is.






    const Input = ( id ) => <div>id</div>

    class Foo extends React.Component
    state =
    arr: [
    <Input id=1 />,
    <Input id=2 />,
    <Input id=3 />,
    <Input id=4 />,
    ],
    id: 5,


    addToArray = () =>
    const arr = [...this.state.arr, <Input id=this.state.id />]
    this.setState(prevState => ( arr, id: prevState.id + 1 ))


    removeFromArray = () =>
    const id = parseInt(window.prompt("Enter index"))

    this.setState(prevState => (
    arr: prevState.arr.filter(element => element.props.id !== id),
    ))


    render()
    return (
    <div>
    <div>
    <button onClick=this.addToArray>Add to array</button>
    </div>
    <div>
    <button onClick=this.removeFromArray>Remove from array</button>
    </div>
    Array: this.state.arr
    </div>
    )



    ReactDOM.render(<Foo />, document.getElementById("root"))

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>








    share|improve this answer



























      1














      You have a number of syntax errors in your original code, and you're not following best practices (e.g. if you're referencing state when using setState, use the callback because setState is asynchronous), but I think the primary issue you were having is that you're comparing strings to numbers.



      I refactored your code to use more current methods (i.e. ES6) and added parseInt to convert the input from window.prompt into a number that can be compared to your <Input /> component’s id prop. I also switched the explicit <Input /> declarations to use a numeric input, rather than a string.



      Hit run and you'll see that it works as-is.






      const Input = ( id ) => <div>id</div>

      class Foo extends React.Component
      state =
      arr: [
      <Input id=1 />,
      <Input id=2 />,
      <Input id=3 />,
      <Input id=4 />,
      ],
      id: 5,


      addToArray = () =>
      const arr = [...this.state.arr, <Input id=this.state.id />]
      this.setState(prevState => ( arr, id: prevState.id + 1 ))


      removeFromArray = () =>
      const id = parseInt(window.prompt("Enter index"))

      this.setState(prevState => (
      arr: prevState.arr.filter(element => element.props.id !== id),
      ))


      render()
      return (
      <div>
      <div>
      <button onClick=this.addToArray>Add to array</button>
      </div>
      <div>
      <button onClick=this.removeFromArray>Remove from array</button>
      </div>
      Array: this.state.arr
      </div>
      )



      ReactDOM.render(<Foo />, document.getElementById("root"))

      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
      <div id="root"></div>








      share|improve this answer

























        1












        1








        1







        You have a number of syntax errors in your original code, and you're not following best practices (e.g. if you're referencing state when using setState, use the callback because setState is asynchronous), but I think the primary issue you were having is that you're comparing strings to numbers.



        I refactored your code to use more current methods (i.e. ES6) and added parseInt to convert the input from window.prompt into a number that can be compared to your <Input /> component’s id prop. I also switched the explicit <Input /> declarations to use a numeric input, rather than a string.



        Hit run and you'll see that it works as-is.






        const Input = ( id ) => <div>id</div>

        class Foo extends React.Component
        state =
        arr: [
        <Input id=1 />,
        <Input id=2 />,
        <Input id=3 />,
        <Input id=4 />,
        ],
        id: 5,


        addToArray = () =>
        const arr = [...this.state.arr, <Input id=this.state.id />]
        this.setState(prevState => ( arr, id: prevState.id + 1 ))


        removeFromArray = () =>
        const id = parseInt(window.prompt("Enter index"))

        this.setState(prevState => (
        arr: prevState.arr.filter(element => element.props.id !== id),
        ))


        render()
        return (
        <div>
        <div>
        <button onClick=this.addToArray>Add to array</button>
        </div>
        <div>
        <button onClick=this.removeFromArray>Remove from array</button>
        </div>
        Array: this.state.arr
        </div>
        )



        ReactDOM.render(<Foo />, document.getElementById("root"))

        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
        <div id="root"></div>








        share|improve this answer













        You have a number of syntax errors in your original code, and you're not following best practices (e.g. if you're referencing state when using setState, use the callback because setState is asynchronous), but I think the primary issue you were having is that you're comparing strings to numbers.



        I refactored your code to use more current methods (i.e. ES6) and added parseInt to convert the input from window.prompt into a number that can be compared to your <Input /> component’s id prop. I also switched the explicit <Input /> declarations to use a numeric input, rather than a string.



        Hit run and you'll see that it works as-is.






        const Input = ( id ) => <div>id</div>

        class Foo extends React.Component
        state =
        arr: [
        <Input id=1 />,
        <Input id=2 />,
        <Input id=3 />,
        <Input id=4 />,
        ],
        id: 5,


        addToArray = () =>
        const arr = [...this.state.arr, <Input id=this.state.id />]
        this.setState(prevState => ( arr, id: prevState.id + 1 ))


        removeFromArray = () =>
        const id = parseInt(window.prompt("Enter index"))

        this.setState(prevState => (
        arr: prevState.arr.filter(element => element.props.id !== id),
        ))


        render()
        return (
        <div>
        <div>
        <button onClick=this.addToArray>Add to array</button>
        </div>
        <div>
        <button onClick=this.removeFromArray>Remove from array</button>
        </div>
        Array: this.state.arr
        </div>
        )



        ReactDOM.render(<Foo />, document.getElementById("root"))

        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
        <div id="root"></div>








        const Input = ( id ) => <div>id</div>

        class Foo extends React.Component
        state =
        arr: [
        <Input id=1 />,
        <Input id=2 />,
        <Input id=3 />,
        <Input id=4 />,
        ],
        id: 5,


        addToArray = () =>
        const arr = [...this.state.arr, <Input id=this.state.id />]
        this.setState(prevState => ( arr, id: prevState.id + 1 ))


        removeFromArray = () =>
        const id = parseInt(window.prompt("Enter index"))

        this.setState(prevState => (
        arr: prevState.arr.filter(element => element.props.id !== id),
        ))


        render()
        return (
        <div>
        <div>
        <button onClick=this.addToArray>Add to array</button>
        </div>
        <div>
        <button onClick=this.removeFromArray>Remove from array</button>
        </div>
        Array: this.state.arr
        </div>
        )



        ReactDOM.render(<Foo />, document.getElementById("root"))

        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
        <div id="root"></div>





        const Input = ( id ) => <div>id</div>

        class Foo extends React.Component
        state =
        arr: [
        <Input id=1 />,
        <Input id=2 />,
        <Input id=3 />,
        <Input id=4 />,
        ],
        id: 5,


        addToArray = () =>
        const arr = [...this.state.arr, <Input id=this.state.id />]
        this.setState(prevState => ( arr, id: prevState.id + 1 ))


        removeFromArray = () =>
        const id = parseInt(window.prompt("Enter index"))

        this.setState(prevState => (
        arr: prevState.arr.filter(element => element.props.id !== id),
        ))


        render()
        return (
        <div>
        <div>
        <button onClick=this.addToArray>Add to array</button>
        </div>
        <div>
        <button onClick=this.removeFromArray>Remove from array</button>
        </div>
        Array: this.state.arr
        </div>
        )



        ReactDOM.render(<Foo />, document.getElementById("root"))

        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
        <div id="root"></div>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 2:38









        coreywardcoreyward

        50.8k1597126




        50.8k1597126





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55034472%2fremoving-an-element-from-array-not-working%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved