iterating Javascript array and delete based on condition - javascript

I want to iterate through an array of words, look up the definition and delete the word if no definition is found.
my code looks as follows;
var words = ["word1", "word2", "word3",]
function Meaning(words){
const getMeaning = async () => {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${words}`)
const myJson = await response.json()
for(i = 0; i < words.length; ++i) {
if(!response[i]){
myJson.splice(i,1)
console.log(myJson)
}
}}
This is not really doing anything atm. Where am I going wrong?
edit to add context
tried like this as well;
for(i = 0; i < words.length; ++i)
fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${words[i]}`).then((response) => {
if (response === 404) {
let response = words
words[i].splice(i,1)
console.log(response)
}
throw new Error('Something went wrong');
})
.then((responseJson) => {
let response = words
response[i].splice(i,1)
})
.catch((error) => {
console.log(error)
});
I can print out the 404 error when it finds no definition, but I can't remove it from the words array

After quick look at the API, and it appears to handle only single words, so the caller needs to make the requests one at a time. Here's how to do it...
const baseUrl = 'https://api.dictionaryapi.dev/api/v2/entries/en/';
// one word lookup. resolve to an array of definitions
async function lookupWord(word) {
const res = await fetch(baseUrl + word);
return res.json();
}
// resolve to a bool, true if the word is in the corpus
async function spellCheck(word) {
const defArray = await lookupWord(word);
return Array.isArray(defArray) && defArray.length > 0;
}
// create a spellCheck promise for every word and resolve with the results
// note, this mutates the array and resolves to undefined
async function spellCheckWords(array) {
const checks = await Promise.all(array.map(spellCheck));
for (let i=array.length-1; i>=0; i--) {
if (!checks[i]) array.splice(i,1);
}
}
// test it (a little)
let array = ['hello', 'whereforeartthou', 'coffee'];
spellCheckWords(array).then(() => {
console.log(array)
})

try this code, you need to check every single element of array from response
var words = ["word1", "word2", "word3"];
function Meaning(words) {
const getMeaning = async () => {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${words}`)
const myJson = await response.json()
let result = [];
myJson.forEach(element => {
if(words.includes(element)) {
result.push(element)
}
});
return result;
}
return getMeaning();
}

Related

array return value is always empty

i'm trying to program a prototype right now, however i have a problem, my return values, my output overall always returns an empty array.
If I put everything into a function it works, but if I divide everything into code blocks it doesn't work anymore.
I always get an empty array back as I said.
What am I doing wrong?
async function dataLength(){
return new Promise((resolve, reject) => {
pdo.query(`SELECT * FROM mainsites`, function(err, result) {
let results = result;
let resultsLength = results.length;
let dataIndexMainId = [];
for(let index = 0; index < resultsLength; index++){
dataIndexMainId[index] = results[index]["id"];
}
resolve();
})
})
}
async function getSubSitesIndex(length){
let dataSitesIndex = [];
for(let i = 0; i <= length; i++){
await new Promise((resolve) => {
pdo.query("SELECT * FROM subsites WHERE main = ?",[i] , function(err, result) {
dataSitesIndex[i] = result;
resolve();
})
})
}
let filterDataSitesIndex = dataSitesIndex.filter(String);
console.log(filterDataSitesIndex);
return filterDataSitesIndex;
}
async function getIndex(paramIndex){
let indexResult = await paramIndex;
let indexArray = [];
for (let indexRes of indexResult){
for(let res of indexRes){
indexArray.push(res);
}
}
return indexArray;
}
if I execute the code like this
getIndex(
await getSubSitesIndex(
await dataLength()
)
);
In dataLength, your pdo.query call is not properly promisified.
However, you shouldn't have to write 3 functions for this at all. Do not make multiple queries to your database. Use a single query that does a JOIN - much more efficient!
function getIndex() {
return new Promise((resolve, reject) => {
pdo.query(`
SELECT mainsites.id AS main_id, subsites.id AS sub_id
FROM mainsites
JOIN subsites ON subsites.main = mainsites.id;
`, [], (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}

Javascript "for of" loop not returning value

async function getMultiBalances() {
let chains = await getAllChains();
let address = await getAddress();
let totalBalances = [];
for (let chain of chains) {
let chainId = chain.chain_id;
let balances = await getMultichainBalancesArray(chainId, address);
if (balances != undefined) {
totalBalances = [...balances, ...totalBalances];
}
}
console.log(totalBalances);
return totalBalances;
}
The above code console logs nothing and returns nothing.
Now.. If I move the console log and return statement into the "for of" loop it will return the first iteration and work fine. I don't understand why I can't return the final value outside of the for of loop to get the array I actually want.
async function getMultiBalances() {
let chains = await getAllChains();
let address = await getAddress();
let totalBalances = [];
for (let chain of chains) {
let chainId = chain.chain_id;
let balances = await getMultichainBalancesArray(chainId, address);
if (balances != undefined) {
totalBalances = [...balances, ...totalBalances];
}
console.log(totalBalances);
return totalBalances;
}
}

Trying to use replace() method on files by passing the string not working - JS

I'm trying to replace a string, but when i try to do it on a file, it does not work. Or only the last file will work.
Main Code (inside a class method):
const funcs = fs.readdirSync(path.join(__dirname, "../funcs")).filter(file => file.endsWith('.js'));
this.functions = this.code.split("$");
const functions = this.functions
for (const func of funcs) {
for (let x = functions.length - 1; x > 0; x--) {
let i = 0;
const res = await require(`../funcs/${func}`)(client, this.code.toString(), this._author);
console.log(x);
console.log(res);
console.log(functions);
return res;
i++;
}
}
ping.js:
const ping = (client, code, author) => {
const result = code.split("$[ping]").join(client.ws.ping)
return result;
}
module.exports = ping;
messageAuthorTag.js:
const Util = require('../utils/util');
const messageAuthorTag = (client, code, author) => {
if (code === null) return;
const res = code.split("$[message.author.tag]").join(`${author.tag}`);
return res;
}
module.exports = messageAuthorTag;
Using it : "ping: $[ping] author tag: $[message.author.tag]"
Output:
ping: $[ping] author tag: Example#0001
Your issue is that you return res in the middle of a for loop. This means it won't do anything else in the function and will skip the rest of the loops (like running the other functions!)
As an additional note, you could also remove the let i = 0 and i++ since that doesn't seem to be used for anything.

Trying to get the function to return the arr with the pushed data in it, but for some reason its not returning it there

Here I have required the sql in my main index file
seeded the database and checked that the sql query returns
// require sql connection from main index
const connection = require('./index');
async function tow() {
let arr = [];
let one = await connection.query("Select name FROM department", (err, res) => {
if (err) throw err;
// console.log(res);
console.log('1'arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
});
console.log('3',arr);
return one;
}
// I want this function to return array with the pushed elements
tow();
You need to return arr. Also you are mixing the promise style with the callback style of async, you can do either one, but not a mix. Try something like this.
If connection.query returns a promise:
async function tow() {
let arr = [];
let one = await connection.query("Select name FROM department").then(res => {
// console.log(res);
console.log('1', arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
return arr; // need to return arr
},
err => console.error(err));
console.log('3',arr);
return one;
}
tow().then(res => console.log('result', res));
In your case, where connection.query expects a callback function, you can convert the callback to a promise like this.
function tow() {
return new Promise((resolve, reject) => {
let arr = [];
connection.query("Select name FROM department", (err, res) => {
if (err) reject();
// console.log(res);
console.log('1', arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
resolve(arr);
});
})
}
// I want this function to return array with the pushed elements
tow().then(res => console.log('result', res));
Here's a codeSandbox

Looping through a list of fetch() calls

I'm trying to loop through a bunch of data and make asynch calls. However, I'm not getting the syntax right
async function getEmailData(conversationId){
fetch(aysynch)
.then(response => {return response.json(); })
.then(data => {
dictionary = {}
console.log(data)
var info = data.Body.ResponseMessages.Items[0].Conversation.ConversationNodes[0].Items[0]
console.log(info)
var conversationId = info.ConversationId.Id
var from = info.From.Mailbox.EmailAddress
var to = info.ToRecipients.map(function(recipient) {return recipient.EmailAddress})
var date = info.DateTimeReceived
dictionary[conversationId] = {'from':from, 'to': to, 'date': date}
return dictionary
})
}
x = [listOfIds] //10 in total
for (i=0; i<x.length; i++) {
console.log(x[i].ConversationId.Id)
let response = await getEmailData(x[i].ConversationId.Id)
let data = await response
console.log(data)
}
This is printing out all of the ID's and then grabbing the list id in x and running that one 10 times. How do I make the aysnch request for each request?
Some issues:
The function getEmailData is not returning anything. You need to return the result of the promise chain.
async has no use if you don't use await inside such a function
await outside an async function is invalid.
await response is not useful when response is already the result of an await
declare your variables (with let, var, const)
So do this:
function getEmailData(conversationId){
return fetch(aysynch)
.then(response => response.json())
.then(data => {
const dictionary = {};
console.log(data);
var info = data.Body.ResponseMessages.Items[0].Conversation.ConversationNodes[0].Items[0];
console.log(info);
var conversationId = info.ConversationId.Id;
var from = info.From.Mailbox.EmailAddress;
var to = info.ToRecipients.map(recipient => recipient.EmailAddress);
var date = info.DateTimeReceived;
dictionary[conversationId] = {from, to, date};
return dictionary;
});
}
(async function() {
let x = [1, 2, 4, 6, 9, 13, 23, 22, 24, 19]; //10 in total
for (let i=0; i<x.length; i++) {
console.log(x[i].ConversationId.Id);
let data = await getEmailData(x[i].ConversationId.Id);
console.log(data);
}
})(); // Immediately invoked
You should use let. You are are declaring a global variable i.
for (let i = 0; i < x.length; i++) {
console.log(x[i].ConversationId.Id)
let response = await getEmailData(x[i].ConversationId.Id)
let data = await response
console.log(data)
}

Categories

Resources