xxxxxxxxxx
const products = [
{ name: 'Laptop', price: 32000, brand: 'Lenovo', color: 'Silver' },
{ name: 'Phone', price: 700, brand: 'Iphone', color: 'Golden' },
{ name: 'Watch', price: 3000, brand: 'Casio', color: 'Yellow' },
{ name: 'Aunglass', price: 300, brand: 'Ribon', color: 'Blue' },
{ name: 'Camera', price: 9000, brand: 'Lenovo', color: 'Gray' },
];
//Get products that price is greater than 3000 by using a filter
const getProduct = products.filter(product => product.price > 3000);
console.log(getProduct)
//Expected output:
/*[
{ name: 'Laptop', price: 32000, brand: 'Lenovo', color: 'Silver' },
{ name: 'Camera', price: 9000, brand: 'Lenovo', color: 'Gray' }
]
*/
xxxxxxxxxx
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filter = arr.filter((number) => number > 5);
console.log(filter); // [6, 7, 8, 9]
xxxxxxxxxx
const filterThisArray = ["a","b","c","d","e"]
console.log(filterThisArray) // Array(5) [ "a","b","c","d","e" ]
const filteredThatArray = filterThisArray.filter((item) => item!=="e")
console.log(filteredThatArray) // Array(4) [ "a","b","c","d" ]
xxxxxxxxxx
const arr = [1, 2, 3, 4, 5, 6];
const filtered = arr.filter(el => el === 2 || el === 4); //[2, 4]
xxxxxxxxxx
const numbers = [5, 13, 7, 30, 5, 2, 19];
const bigNumbers = numbers.filter(number => number > 20);
console.log(bigNumbers);
//Output: [30]
xxxxxxxxxx
const grades = [10, 2, 21, 35, 50, -10, 0, 1];
// get all grades > 20
const result = grades.filter(grade => grade > 20); // [21, 35, 50];
// get all grades > 30
grades.filter(grade => grade > 30); // [35, 50]
xxxxxxxxxx
const videos = ['html', 'css', 'javascript'];
//filter return multiple values in array
const shortSearch = videos.filter(function (video) {
return video.length <= 5;
});
console.log(shortSearch);
const games = [
{ title: 'Mass Effect', rating: 9.5 },
{ title: 'League of Legends', rating: 5 },
{ title: 'Last of Us', rating: 10 },
{ title: 'God of War', rating: 8.5 },
{ title: 'WWE 2k20', rating: 6 },
];
const goodGames = games.filter(function (game) {
return game.rating > 8;
});
console.log(goodGames);
xxxxxxxxxx
let arr = [1, 2, 3, 4, 5]; // filter function in JS
let newArr = arr.filter((item) => {
return item % 2 == 0;
})
console.log(newArr)
// -- filters the array and return those items which are even
xxxxxxxxxx
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {
return n > 5;
});
xxxxxxxxxx
var jsonarr = [
{
id: 1,
name: "joe"
},
{
id: -19,
name: "john"
},
{
id: 20,
name: "james"
},
{
id: 25,
name: "jack"
},
{
id: -10,
name: "joseph"
},
{
id: "not a number",
name: "jimmy"
},
{
id: null,
name: "jeff"
},
]
var result = jsonarr.filter(user => user.id > 0);
console.log(result);