Frage

I have a object like this

myArray = [
              { name: "1",
                age: "20"
               },         
              { name: "6",
                age: "20"
               },  
              { name: "2",
                age: "20"
               },  
             ];

  anotherArray = [2,1,3,4,5,6];

Basically I am trying to find if match a exists, if it does then delete it from myArray

    for(var i = 0, len = myArray.length; i < len; i++) {
      var searchTerm = myArray[i].name;
      for (var j = 0; j < anotherArray.length; j++) {
      if (myArray[i].name === anotherArray[j]) {
        // Not exactly sure how the deletion will work with array.splice
        len--;
        break;
    }
   }
  }

For some reason it does not seem to be working as expected.

The end result should be this

   myArray = [         
              { name: "6",
                age: "20"
               } 
             ];
War es hilfreich?

Lösung 3

There are a few issues. There is a trailing comma in the myArray array literal that is incorrectly treated as an elision in IE, so the array has a length that is too long. Also, anotherArray includes all the members of myArray, so if the function works, it removes all of them.

You can use splice to remove members from an array. It affects the length and in an incrementing loop means you'll skip the next member if you don't modify the counter. The usual strategy is to use a decrementing loop to avoid those issues.

Lastly, the "name" property is a string but the values in anotherArray are numbers, which might mess with the comparison.

myArray = [
              { name: "1",
                age: "20"
               },         
              { name: "6",
                age: "20"
               },  
              { name: "2",
                age: "20"
               }                   // trailing comma removed
             ];

  anotherArray = [2,1,3,4,5];  // 6 removed so one member remains


for (var i=myArray.length - 1; i >= 0; i--) {
  // Convert name to a number since indexOf uses ===
  if (anotherArray.indexOf(+myArray[i].name) != -1) {
    myArray.splice(i, 1);
  }
}

console.log(myArray[0].name);

A polyfill for indexOf can be found at MDN.

Andere Tipps

You've got several things going on here that are going to give you trouble. For one thing, using the string equality operator === will prevent any kind of type coercion from being done, meaning that "1" and 1 will not be equal. If you wish to perform a type conversion, you should use the == equality operator:

"1" === 1;
=> false

"1" == 1;
=> true

Additionally, it seems to me that you are over complicating things with this method. If you wish to remove all objects from your array whose name is contained in anotherArray, you should use the standard Array.prototype.filter method to produce the array you want:

var myArray = [{name: "1", age: "20"}, 
               {name: "6", age: "20"}, 
               {name: "2", age: "20"}],
    anotherArray = [2,1,3,4,5,6];

myArray = myArray.filter(function(e) {
 return (a.indexOf(e.name|0) < 0)   // note: e.name|0 will convert the string 
});                                 // value of e.name to an integer
=> [];

A couple things to note about the code you posted:

  1. Because anotherArray is declared without a preceding var and is not part of a comma-separated var statement, it will be instantiated as a global variable. This behavior is highly undesirable and can result in some very strange errors in your code.
  2. You stated that you expect the result of your deletion to result in the following array:

    myArray = [{name: "6", age: "20"}]

    however, notice that 6 is an element in anotherArray and therefore your resulting array should actually be empty.

You're comparing two diferent things (types) as myArray[i].name is a String Object and anotherArray[j] is a Number Object. You should convert one of them OR use the equality operator ("=="), instead of strict equality operator("==="). For further reference see MDN

Even though it might be viewed as poor code you can delete using the delete keyword (as remembered by @RobG, it will not change the length, leaving a empty reference):

...
if (myArray[i].name === anotherArray[j]) {
    delete myArray[i];
...

Array.prototype.filter should do it:

myArray.filter(function(i) { return Array.prototype.indexOf([2,1,3,4,5,6], i.name) })

But the result will include the objects with name in [1,2,6]

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top