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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко