I have an array blackList where I store blacklisted business names, now I have a results array of objects with many business, I want to store in an array the business names which are not included in the blackListed array, what is the easier and most performant way to do this?
Is a nested loop really needed for this?
blackList = [ "Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds", "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company" ,
"Rodilla", "Rodilla Campamento", "Granier", "Llaollao" , "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
"Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"],
list = [ { name:'business 1' }, { name:'business 2' }, { name:'business 3' } ]
The easiest way to do this is to use filter and destructuring:
const blackList = ["Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds", "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company",
"Rodilla", "Rodilla Campamento", "Granier", "Llaollao", "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
"Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"
];
const list = [{
name: 'business 1'
}, {
name: 'business 2'
}, {
name: 'business 3'
}, {
name: "Granier"
}];
const notOnBlacklist = list.filter(({ name }) => !blackList.includes(name));
console.log(notOnBlacklist);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Try
let blackList =
{"Dominos Pizza":1, "Domino's Pizza":1, "McDonald's":1, "McDonalds":1
,"Telepizza":1, "Subway":1, "Burger King":1, "KFC":1, "Pans&Co":1
,"Pans&Company":1, "Rodilla":1, "Rodilla Campamento":1, "Granier":1
,"Llaollao":1, "Taco Bell":1, "Wendy's":1, "Dunkin' Donuts":1, "Pizza Hut":1
,"Papa John's Pizza":1, "Little Caesars":1, "Panera Bread":1, "Chipotle":1
,"Papa Murphy's":1, "Hungry Howie":1, "Chipotle Mexican Grill":1
,"Starbucks":1 };
let list = [];
addBusiness("'business 1'");
addBusiness("Domino's Pizza");
addBusiness("'business 2'");
addBusiness("Hungry Howie");
addBusiness("'business 3'");
console.log(list);
function addBusiness (name) {
if (blackList.hasOwnProperty(name)) return;
list.push({'name':name});
}
Related
By array intersection I mean, the inventory has a lot more elements than each document ingredients array, and the result I want to get from the query is all documents which all array elements are contained within the inventory. $all will get me zero results since the inventory has more elements than can be found in ingredients even if all ingredients are found within the inventory,
I have thousands of docs that have an array field of strings
{
...
recipe: "recipe1",
ingredients: [ "1 cup cooked quinoa", "6 tbsp butter", "1 large egg" ]
...
},
{
...
recipe: "recipe2",
ingredients: [ "2 lemons", "2 tbsp butter", "1 large egg" ]
...
}
{
...
recipe: "recipe3",
ingredients: [ "1lb salmon", "1 pinch pepper", "4 spears asparagus" ]
...
}
and I'm trying to find all documents where all elements in the ingredients array are contained in a sample array that contains lots of elements, lets say for the case this only contains this:
inventory = [ "lemons", "butter", "egg", "milk", "bread", "salmon", "asparagus", "pepper" ]
With this inventory array, I want to get recipe2 and recipe3.
Right now I have this inventory array and query (thanks to turivishal):
let inventory = ["lemons", "butter", "egg", "milk", "bread", "salmon", "asparagus", "pepper"];
inventory = inventory.map((i) => new RegExp(i, "i"));
query:
Recipe.find({
ingredients: { $all: inventory }
})
Expected result:
{
...
recipe: "recipe2",
ingredients: [ "2 lemons", "2 tbsp butter", "1 large egg" ]
...
}
{
...
recipe: "recipe3",
ingredients: [ "1lb salmon", "1 pinch pepper", "4 spears asparagus" ]
...
}
But I'm getting zero results
You can try aggregation operator in mquery using $expr expression condition,
first of all you can join the array of string by | order symbol and make a string, and use it in $regex search,
$filter to iterate loop of ingredients
$regexMatch to match element has any matching word
$size to get the total size of filtered elements
$eq to match filtered result and actual ingredients is equal
let inventory = ["lemons", "butter", "egg", "milk", "bread", "salmon", "asparagus", "pepper"];
let inventoryStr = inventory.join("|");
// "lemons|butter|egg|milk|bread|salmon|asparagus|pepper"
Recipe.find({
$expr: {
$eq: [
{
$size: {
$filter: {
input: "$ingredients",
cond: {
$regexMatch: {
input: "$$this",
regex: inventoryStr,
options: "i"
}
}
}
}
},
{ $size: "$ingredients" }
]
}
})
Playground
I have an api from which I want to display the data, I have 2 arrays I think each one has category how would I iterate and display these 2 categories, so category Arts and category Entertainment.I would really appreciate the help. Thanks in advance
import React,{useState, useEffect} from 'react'
import './Home.css'
import Books from './Books'
const url="https://json-api-smaiil.herokuapp.com/books"
const Home = () => {
const [loading, setLoading] = useState(true)
const [books, setBooks] = useState([])
const fetchData =async()=>{
setLoading(true)
const response = await fetch(url)
const books = await response.json()
console.log(books)
setBooks(books)
}
useEffect(()=>{
fetchData();
},[])
return (
<div>
<h1 className='categories'>Categories</h1>
{books[0].map((book)=>{
return <li key={book.id}>{book.category}</li>
})}
</div>
)
}
export default Home
[
"Arts":[{
"category": "Arts"
Language: "English"
Narrated by: "Faith G. Harper PhD LPC-S ACS ACN"
Regular price: "$17.47"
Release date: "03-20-18"
bookName: "Unf--k Your Brain"
by: "Faith G. Harper PhD LPC-S ACS ACN"
category: "Arts and Entertainment"
id: "1"
},
{
Language: "English"
Length: "1 hr and 33 mins"
Narreted by: "James Taylor"
Regular price: "$9.95"
Release date: "01-31-20"
Series: "Words + Music"
bookName: " Break Shot: My First 21 Years"
by: "James Taylor"
id: "2"
}],
"Entertainment":[{
"category" :"Entertainment"
"id": "9",
"image": "https://m.media-amazon.com/images/I/51tpSb0iy+L._SL500_.jpg",
"bookName": "The Hiding Place",
"by": "Corrie ten Boom, John Sherrill, Elizabeth Sherrill",
"Narreted by": "Wanda McCaddon",
"Length": "8 hrs and 14 mins",
"Release date": "10-03-11",
"Language": "English",
"rating": "6,641 ratings",
"Regular price": "$24.95",
},
{
Language: "English"
Length: "1 hr and 7 mins"
Narreted by: "Aidan Gillen"
Regular price: "$9.95"
Release date: "03-31-15"
bookName: "The Art of War"
by: "Sun Tzu"
id: "12"
rating: "19,765 ratings"
}]
]
I can't comment because I don't have enough reputation, but it looks like you're using map wrong.
Array.prototype.map's callback takes in currentValue, index, and array Array.prototype.map as arguments. You can get the id, and category from the currentValue by destructuring (notice the curly brackets):
//...
books[0].map(({id, category}) => {
//...
I have an array of objects - I want to change one of the object keys to something else without mutating the original array. what is the best method to approach this?
I understand that I could be using the Map method but unsure how this would work. thanks
const books = [
{ title: "To Kill a Mockingbird", writtenBy: "Harper Lee" },
{ title: "A Clockwork Orange", author: "Anthony Burgess" },
{ title: "The Elephant Tree", writtenBy: "R.D. Ronald" }
]
function changeKey(arr, keyChange, newKey) {
}
// i want to return so the KEY keyChange(author) is changed to newKey(writtenBy)
[
{ title: "To Kill a Mockingbird", writtenBy: "Harper Lee" },
{ title: "A Clockwork Orange", writtenBy: "Anthony Burgess" },
{ title: "The Elephant Tree", writtenBy: "R.D. Ronald" }
]
You can map the parameter array and copy each of the objects within it shallowly using the spread operator. For each new object, if it contains the key we'd like to remove, copy the value to the new key and delete the old key.
const books = [ {title: "To Kill a Mockingbird", writtenBy: "Harper Lee"}, {title: "A Clockwork Orange", author: "Anthony Burgess"}, {title: "The Elephant Tree", writtenBy: "R.D. Ronald"} ];
const changeKey = (arr, keyChange, newKey) =>
arr.map(e => {
const o = {...e};
if (keyChange in o) {
o[newKey] = o[keyChange];
delete o[keyChange];
}
return o;
})
;
console.log(changeKey(books, "author", "writtenBy"));
console.log(books);
Array helpers like map, filter, reduce, etc doesn't mutate the original array they return a new array. Map receives a function as an argument (callback). Map iterate the array applying your callback in every element.
const books = [ {title: "To Kill a Mockingbird", writtenBy: "Harper Lee"},
{title: "A Clockwork Orange", author: "Anthony Burgess"},
{title: "The Elephant Tree", writtenBy: "R.D. Ronald"} ];
//Function to use as a callback on map
function changeKey(current) {
if(current.author) return { title: current.title, writtenBy: current.author };
return current;
}
//Creating new array applying changeKey in every element thanks to map
const newBooks = books.map(changeKey);
console.log(newBooks);
The following will not mutate books array.
const books = [
{ title: "To Kill a Mockingbird", writtenBy: "Harper Lee" },
{ title: "A Clockwork Orange", author: "Anthony Burgess" },
{ title: "The Elephant Tree", writtenBy: "R.D. Ronald" }
];
const renamedBooks = books.map(book => {
if (book.author) {
return {
title: book.title,
writtenBy: book.author
};
}
return book;
});
console.info(renamedBooks);
I have two separate arrays of objects. How can I match properties in one array of objects to another property in the second array?
I need to match the cars use in the const cars with the searchingUse in the const buyers.
const cars = [
{ model:convertible,
year:2015,
use:sports
},
{ model:wagon,
year:2013,
use:family
}
]
const buyers =[
{ name:John
searchingUse: family,
maxYear: 2014,
maxPrice:15000
},
{ name: Mark
searchingUse: sedan,
maxYear: 2012,
maxPrice:1000
}
]
The expected output would be a string listing all the cars that match with each buyers desired use
I greatly appreciate any help!
Thanks
I think you want something like this:
const cars = [
{ model: "convertible", year: "2015", use: "sports" },
{ model: "wagon", year: "2013", use: "family" }
];
const buyers = [
{ name: "John", searchingUse: "family", maxYear: "2014", maxPrice: "15000" },
{ name: "Mark", searchingUse: "ddd", maxYear: "2012", maxPrice: "1000" }
];
const a = buyers
.map(buyer => ({
[buyer.name]: cars.filter(car => car.use === buyer.searchingUse)
}));
console.log(a);
I am attempting to access one of the object propertie through a bracket notation, but I can not figure out why it is not working. As always, Your help is greatly appreciated!
js:
var dude = [
{
question1: "What is dude's favourite food?",
choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer1: 1
},
{
question2: "What was dude's first ever job?",
choices2: ["Staples", "Vodafone", "Costa", "Post office"],
answer2: 0
},
]
var counter = 1;
var currentQues = "question"+counter;
console.log(dude[currentQues]);
The console returns "undefined". Is this because it can not access a property through a variable(currentQues), which essentially holds another variable(counter)?
As always, your help is greatly appreciated. I am just a beginner looking to advance.
dude refers to an array of objects. You're trying to access question1 on dude, but you need to access it on dude[0]:
console.log(dude[0][currentQues]);
// -------------^^^
Live Example:
var dude = [
{
question1: "What is dude's favourite food?",
choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer1: 1
},
{
question2: "What was dude's first ever job?",
choices2: ["Staples", "Vodafone", "Costa", "Post office"],
answer2: 0
},
]
var counter = 1;
var currentQues = "question"+counter;
console.log(dude[0][currentQues]);
I would strongly recommend reconsidering that data structure. The names of the properties of the objects should be the same for all the objects, with just their position in the array differentiating them:
var dude = [{
question: "What is dude's favourite food?",
choices: ["Pizza", "Pasta", "Chips", "Ice cream"],
answer: 1
},
{
question: "What was dude's first ever job?",
choices: ["Staples", "Vodafone", "Costa", "Post office"],
answer: 0
},
]
dude.forEach(function(entry, index) {
var num = index + 1;
console.log("Question #" + num + ": " + entry.question);
});
You need to take the index of the array as well.
var dude = [{ question1: "What is dude's favourite food?", choices1: ["Pizza", "Pasta", "Chips", "Ice cream"], answer1: 1 }, { question2: "What was dude's first ever job?", choices2: ["Staples", "Vodafone", "Costa", "Post office"], answer2: 0 }],
counter = 1;
currentQues = "question" + counter;
console.log(dude[counter - 1][currentQues]);
// ^^^^^^^^^^^