简体   繁体   中英

having trouble targeting element of an array instead of it's position using a for loop

When running this function I keep getting back an array that just returns the first parameter (a). The ultimate goal is to return an array that finds any match to the second parameter (b) and remove it from the first parameter. I've included two test functions below. I've been working on it for a while and it seems like it's just ignoring the condition in my 'if' statement. Can anyone spot why? I'm also open to cleaner ways to do this, as I'm still learning JavaScript. Thanks in advance!

function array_diff(a, b) {
  var newArr = [];
  for ( i = 0; i < a.length; i++) {
    if (b !== a[i]) {
      newArr.push(a[i]);
    }
  } 
  return newArr;
}

array_diff([1,2,2,2,3],[2]);
array_diff([1,2],[1]);

The problem is that you're comparing an array to a value.

Because a[i] is a value, b should also be value and not an array so try

array_diff([1,2,2,2,3],2);
array_diff([1,2],1);

ie 2 instead of [2] and 1 instead of [1]

Another way is to change your if condition

if (b[0] !== a[i]) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM