Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate values from array with OR operator

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?

like image 970
Amit Avatar asked Jul 29 '26 21:07

Amit


2 Answers

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:

  • Why is using “for…in” with array iteration a bad idea?

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"`.
like image 98
Nina Scholz Avatar answered Aug 01 '26 10:08

Nina Scholz


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);
like image 31
Mohammad Usman Avatar answered Aug 01 '26 12:08

Mohammad Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!