0

From below code i tried removing data from array. Unfortunately Its not removing data from my array i.e ary , See if you can help me with this challange

var ary = [{"Force":"Force Converter"},{"Power":"Power Converter"}];

 function removeFav(n,v){ 
       var index = ary.indexOf(n);
       alert(index);
       if (index > -1) {
           ary.splice(index, 1);
        }
         alert("New updated Array:"+ary);
   }

Calling to remove as

removeFav("Power","Power Converter");  // this calls the above method
7
  • 1
    Why does your method take a v argument that it never uses? Commented Apr 7, 2015 at 22:09
  • 1
    as written, you need to pass the object in the array, not a string describing the object. Commented Apr 7, 2015 at 22:10
  • @IanKemp thats not a problem. This code is part of my huge application. Keeping v in there for now does not makes diffrence Commented Apr 7, 2015 at 22:11
  • @dandavis How can we do so? Commented Apr 7, 2015 at 22:13
  • like removeFav(ary[0]), which is kinda not very helpful really... Commented Apr 7, 2015 at 22:14

3 Answers 3

1

Your contains function is perfect. This should work for you, just use the name directly as property

function setFavorite(name, value){
 alert(contains(ary, value));

    var obj = {}; 
    obj.name = value; 
    alert(obj.name);
    ary.push(obj);
    alert(contains(ary, obj));
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for your time. i do want to add it in the array , if already exists, here we are writing the contains alert after` ary.push..`
+ One given .. ...becoz i already accepted answer for this question yesterday
Donkey Donkey, two many errors, make yourself comfortable with javascript first, wait I will change the script ..... aaaaa
Hi, jsfiddle.net/pewn1d4m/12 still struggling, its not working as we expected
Did you take a look at the demo in the answer below: I changed the code a bit, so you only have to pass the property to the Contains function. jsbin.com/cayiyo/2
|
1

Note: browser support for indexOf is limited, it is not supported in IE7-8.

Here is a demo Demo and below you can find the code again.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>

        localStorage.clear();

        var ary = [];
        ary.push({ "Force": "Force Converter" })
        ary.push({ "Power": "Power Converter" });

        function contains(arr, k) {
            var doesContain = false;
            for (var i = 0, length = arr.length; i < length; i++) {
                var item = arr[i];
                if (item.hasOwnProperty(k)) {
                    doesContain = true;
                    break;
                }
            }
            return doesContain;
        }

        if (localStorage.getItem("testObject") != null) {
            alert("localstorage has item testobject");
            //Parse the retrieved value into an array
            ary = JSON.parse(localStorage.getItem('testObject'));
        }

        function setFavorite(k, v) {

            var obj = {};
            obj[k] = v;

            var hasItem = contains(ary, k);

            if (!hasItem) {
                ary.push(obj);
                // Put the object into storage
                localStorage.setItem('testObject', JSON.stringify(ary));
            }


            // Retrieve the object from storage
            var retrievedObject = localStorage.getItem('testObject');

            // Parse the retrieved value into an array
            var retrievedArray = JSON.parse(retrievedObject);

            // clear the ouput first
            $("#fab-id").html("");
            //iterate over the array which contains key-value pairs
            for (var i = 0; i < retrievedArray.length; i++) {
                var item = retrievedArray[i];

                var key = Object.keys(item)[0];
                var value = item[key];

                //----------BELOW CODE DOES NOT WORK PROPERLY----   
                $("#fab-id").append('<a>' + value + '</a><br/>');

            }
        }

    </script>
</head>
<body>
    <button id="btn">Click me!</button>
    <button id="btn2">Add another item!</button>

    <div id="fab-id"></div>

    <script>
        //adding a simple click event handler
        document.getElementById("btn").addEventListener("click", function () {
            //setFavorite("Power", "Power Converter");
            //setFavorite("Power", "Power Converter");
            setFavorite("propA", "X");
        });

        document.getElementById("btn2").addEventListener("click", function () {
            //setFavorite("Power", "Power Converter");
            //setFavorite("Power", "Power Converter");
            setFavorite("xyz", "blabal");
        });
    </script>

</body>
</html>

11 Comments

if i declare ary like this: var ary = [{"Force":"Force Converter"},{"Power":"bar"}]; and call the function: removeFav("Power","Power Converter"); it will remove it. your condition should be if(obj.hasOwnProperty(n) && obj[n]===v)
hasOwnProperty means?
checks if the object has that property
@Legends what OMAR ELAWADY is saying in coment?
@Ashutosh ask him ;-)
|
0

Your code is essentially calling ary.indexOf("Power"). But there is no element in ary with the index Power, hence why the call always fails. In fact, Array.indexOf() won't work for your scenario because it only works on simple types, not complex objects.

What you need to do is check for an object with the specified key in that array, and remove said object if it's found. For this you use the Object.hasOwnProperty()method:

function removeFav(key) { 
  for (var i = 0; i < ary.length; i ++) {
    // if the current array item has a property
    // that matches the specified one, remove that item
    if (ary[i].hasOwnProperty(key)){
      ary.splice(i, 1);
      return;
    }  
  }
}

3 Comments

@Ashutosh correct, I just prefer to use variable names that make code more readable.
Thank you for ur explanation. And after this if i do localStorage.setItem('testObject', JSON.stringify(ary)); then it will update new array ,right?
HI, I got new problem, How can i make array to accept only unique item ? i wrote a boolen method here to check but its not working, can you check this here plz jsfiddle.net/pewn1d4m/9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.