Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Fetch values by ignoring a specific one in JavaScript?
To ignore a specific value when fetching data from an array or object, use the logical NOT (!) operator in conditional statements to exclude unwanted values and retrieve only the ones you need.
Using NOT Operator with Array of Objects
The most common approach is to loop through your data and use the inequality operator (!=) to skip specific values:
var customerDetails = [
{
customerName: "John",
customerAge: 28,
customerCountryName: "US"
},
{
customerName: "David",
customerAge: 25,
customerCountryName: "AUS"
},
{
customerName: "Mike",
customerAge: 32,
customerCountryName: "UK"
}
];
for(var i = 0; i < customerDetails.length; i++) {
if(customerDetails[i].customerCountryName != "AUS") {
console.log("The country name is=" + customerDetails[i].customerCountryName);
}
}
The country name is=US The country name is=UK
Using Array Filter Method
A more modern approach uses the filter() method to create a new array excluding specific values:
var customerDetails = [
{customerName: "John", customerAge: 28, customerCountryName: "US"},
{customerName: "David", customerAge: 25, customerCountryName: "AUS"},
{customerName: "Mike", customerAge: 32, customerCountryName: "UK"}
];
// Filter out customers from AUS
var filteredCustomers = customerDetails.filter(customer =>
customer.customerCountryName !== "AUS"
);
filteredCustomers.forEach(customer => {
console.log("Customer: " + customer.customerName + ", Country: " + customer.customerCountryName);
});
Customer: John, Country: US Customer: Mike, Country: UK
Ignoring Multiple Values
To exclude multiple values, use logical operators or the includes() method:
var countries = ["US", "AUS", "UK", "Canada", "Germany"];
var excludeCountries = ["AUS", "Germany"];
// Method 1: Using logical OR
for(var i = 0; i < countries.length; i++) {
if(countries[i] !== "AUS" && countries[i] !== "Germany") {
console.log("Allowed country: " + countries[i]);
}
}
console.log("---");
// Method 2: Using includes()
countries.forEach(country => {
if(!excludeCountries.includes(country)) {
console.log("Allowed country: " + country);
}
});
Allowed country: US Allowed country: UK Allowed country: Canada --- Allowed country: US Allowed country: UK Allowed country: Canada
Comparison of Methods
| Method | Best For | Performance |
|---|---|---|
| for loop with != | Simple exclusions | Fast |
| Array.filter() | Creating new filtered arrays | Moderate |
| includes() with ! | Multiple exclusions | Good |
Conclusion
Use the NOT operator (!) or inequality (!=) to ignore specific values when filtering data. The filter() method provides a cleaner approach for creating new arrays with excluded values.
Advertisements
