3

This is a very simple question but I am not been able to wrap my head around it. I have an array of pages with n number of page names, I want to run a loop with some page names not included in it.

var arr = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page']; 
for (var page in arr) {
     if (arr[page] !== "page-name" || arr[page] !== "some-more") {
        console.log(arr[page])
     }
 }

Now the result that I want is this:

page-name-two
page-3
another-page

What am I doing wrong?

Amit
  • 1,412
  • 1
  • 9
  • 12

3 Answers3

3

Just take logical AND && instead of logical OR ||.

Please use a for loop with a variable for the index instead of the keys of an object.

Source:

var arr = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page']; 
for (var i = 0; i < arr.length; i++) {
     if (arr[i] !== "page-name" && arr[i] !== "some-more") {
        console.log(arr[i]);
     }
 }

The expression

arr[i] !== "page-name" || arr[i] !== "some-more"

is always true, because for exampe if

arr[i] === "page-name"

then the other part is true, because of

"page-name" !== "some-more"`.
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You should use .filter() to filter values from first array and then perform whatever action you want to perform on resultant array. This will save your from writing a lot of OR / AND conditions in case you need to filter more values.

let arr1 = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page'],
    arr2 = ["page-name", 'some-more'];

let result = arr1.filter(s => !arr2.includes(s));

console.log(result);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

I would store the values that you're looking to eliminate, then run Array.filter on your list of all page names to find matches. If a name matches, remove it from the final array.

// This can be a array of whatever strings you're looking to eliminate from the array
const valuesToFilter = ['page-name', 'some-more'];

// Your original array
const arr = ["page-name", "page-name-two", 'page-3', 'some-more', 'another-page']; 

// Use Array.filter to eliminate anything that doesn't pass the filter test
const filteredArr = arr.filter(page => {
  let foundMatch = false;

  valuesToFilter.forEach(value => {
    if (page === value) {
      foundMatch = true;
    }
  })

  if (!foundMatch) return page;
});

console.log(filteredArr);
Snuglas
  • 63
  • 6