2

I'm trying to find the index of an array within an array, but I have forgotten some steps, and I'm not exactly sure if I require another loop.

I will start with an array that contains pushed values like so:

var payments = [["2015-03-10", "100.00"],["2015-03-11", "14.00"]];

When I click on a button with a similar value, I want to remove it from the array.

My buttons will have an onclick function, like so:

onclick="removePayment(this.value)"

The value of the buttons looks like this:

value="' + payments[i][0] + ': $' + payments[i][1] + '"

Which is basically the same as: 2015-03-10: $100.00

I will then (by passing the value as a parameter via onclick), re-create the way it appears as an array value, hoping that I can now capture its index within the "payments" array.

        // We start with a string, like: "2015-03-10: $100.00"
        var amt = val.split(':')[0]; // 100.00
        var date = val.split('$')[1]; // 2015-03-10
        var temp = (amt + ',' + date).split(','); // ["100.00", "2015-03-10"]
        console.log(temp);

        for (i = 0; i < payments.length; i += 1) {
           console.log(payments[i].indexOf(temp)); // returns -1

        }

Thanks in advance!

3 Answers3

1

Use an if clause to test if the two values amt and date are a match. Then store the indices of the matches in an array. Loop that array to delete the matched indices from the payments array.

    // We start with a string, like: "2015-03-10: $100.00"
    var date = val.split(':')[0]; // 100.00
    var amt = val.split('$')[1]; // 2015-03-10

    var indices = [];
    for (i = 0, max = payments.length; i < max; i += 1) {
       if (payments[i][0] == date && payments[i][1] == amt)
       {
           indices.push(i);
       }
    }

    indices.map(function(element){
        payments.splice(element, 1); //delete the indices from the array.
    });
Mouser
  • 13,132
  • 3
  • 28
  • 54
1

You have swapped the values, and put the date in the amt variable and the amount in the date variable. It should be:

var date = val.split(':')[0]; // 2015-03-10
var amt = val.split('$')[1]; // 100.00

You are using both a loop and indexOf, but you only need one of them. Even if it's an array of arrays that you are searching in, you are still only searching for items in the outer array as it's an array you are searching for.

As you are not searching for a value but an object (arrays are objects), you can't use indexOf (as two different objects aren't equal even if they have the same values), so use the loop and compare the items in the array that you are searching for:

var index = -1;
for (i = 0; i < payments.length; i += 1) {
  if (payments[i][0] == date && payments[i][1] == amt) {
    index = i;
    break;
  }
}

Demo:

var payments = [["2015-03-10", "100.00"],["2015-03-11", "14.00"]];

var val = "2015-03-10: $100.00";

var date = val.split(':')[0]; // 2015-03-10
var amt = val.split('$')[1]; // 100.00

var index = -1;
for (i = 0; i < payments.length; i += 1) {
  if (payments[i][0] == date && payments[i][1] == amt) {
    index = i;
    break;
  }
}

document.write(index);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

If you want to find the index/indices within an array where a subarray appears, you could use a mixture of a map and filter, but you'd also need an array equality checking function.

Let's presume we have Array.prototype.equals, per this SO answer, courtesy of @TomášZato, then we can do:

haystackArray.map(function(e, i) { return e.equals(needleArray) ? i : false; })
             .filter(function(e) { return e !== false; });

This will return an array of matching indicies (or an empty array, if the needleArray wasn't found).

// Array equality function by Tomáš Zato
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time 
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].equals(array[i]))
                return false;       
        }           
        else if (this[i] != array[i]) { 
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;   
        }           
    }       
    return true;
};

var subarrayIndexOf = function(haystack, needle) {
    return haystack.map(function(e, i) { return e.equals(needle) ? i : false; })
                   .filter(function(e) { return e !== false; });
};

var haystack = [ [1,2], [3,4], [5,6], [3,4] ],
    needle   = [3,4];

alert('subarray found at indices: ' + subarrayIndexOf(haystack, needle).toString());
Community
  • 1
  • 1
Xophmeister
  • 8,884
  • 4
  • 44
  • 87