0

I'm trying to remove items from an array:

for (var i = 0; i < transformedColumns.length; i++) {
  if (data[0].indexOf(transformedColumns[i] > -1)) {                   
       delete transformedColumns[i];
  }
}

The thing I'm doing Is to check if the value in transformedColumns[i] exists in data[0] array. If It does, the value should be removed from the transformedColumns.

But when I do like above, the whole transformedColumns becomes undefined.

    for (var i = 0; i < transformedColumns.length; i++) {
        if (data[0].indexOf(transformedColumns[i] > -1)) {                   
            transformedColumns.splice(transformedColumns[i], 1);
        }
    }

This works, except that it removes a value from transformedColumns that does not exist in data[0]. Let's say that transformedColumns contains ["Item No", "Item Name", "Item State"] and data[0] contains ["Item No", Item Name"]. The only values that should be removed from transformedColumnes are Item No and Item Name, not Item State.

What am I doing wrong?

1
  • delete: "The delete operator removes a property from an object", Array.prototype.splice(start, deleteCount): "start : Index at which to start changing the array", "deleteCount: An integer indicating the number of old array elements to remove" Commented Aug 14, 2017 at 7:06

1 Answer 1

1
data[0].indexOf(transformedColumns[i] > -1)

You having wrong condition statement. your condition should be

(data[0].indexOf(transformedColumns[i]) >-1 )

You are passing a condition to indexOf which fails

indexOf(transformedColumns[i] > -1)

That is the reason it is returning true for all the cases. Should work after you fix that

 for (var i = 0; i < transformedColumns.length; i++) {
        if (data[0].indexOf(transformedColumns[i]) > -1 ) {                   
            transformedColumns.splice(transformedColumns[i], 1);
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

This is more advisable. Use splice instead of delete since delete will results in vacant space inside array.
.splice(transformedColumns[i], 1) is still wrong. The first parameter of .splice() is an index and not a string.

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.