Get API array number by comparing ''Name'' - javascript

I want to compare the name of a button I press with an array to find the matching name and then select that array number.
I currently have a For loop which gets all the info from every team in the array but I only need a specific one.
for( var i = 0 ; i <data.api.teams.length; i++)
.lenght needs to be the value corresponding to the team name I selected.
So for example: I press a button with the name and value of ''Twente'', I want the a for loop to search through the names to find ''Twente'' and return the number (''6'') as a value in order to use in another loop.
Does anyone know how I can handle this request?
The screenshot shows the API data I get from the call to get all the info I need.

To get array index of the item you can use Array.findIndex
teamIndex = data.api.teams.findIndex(
team => team.name == "Twente";
);

You're making this more complicated than you need to- you don't need a manual loop, just use Array.prototype.findIndex().
From MDN:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
In your case, we'll pass findIndex() a function checking for the name match.
data.api.teams.findIndex(team => team.name == name);

Related

Unable to remove a specific Item from array

I have a simple array as
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I need to remove the first index from this array and it should be of below type
[{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I tried splice as below
arr.splice(1,1)
But it is giving response {"name":"ram","value":"2"}
how to get [{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
It might be very simple question but Im stuck here from sometime.can someone plz help
I think you taking the returning value of Array.prototype.splice().
Array.prototype.splice() returns an array containing the deleted elements.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
arr.splice(1,1)
console.log(arr);
You can compare the difference methods. Be aware if you need change the array or just get a copy to keep with the original one.
Attention: The first array index is 0, not 1. The index one is the second element of the array
The splice method return the element removed from array. That's the reason why you've got the second element from array in your test
Doc: https://bytearcher.com/articles/how-to-delete-value-from-array/
In your question you got the second index that is 1, in order to get the values that was shown, I'll use the index 1 as well.
//DELETE
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
delete arr[1];
console.log("using delete",arr)
//SPLICE METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let firstElement = arr.splice(1,1)
console.log("using splice",arr)
console.log("the method splice return the element removed from array",firstElement )
//FILTER METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let copyArr = arr.filter((element, index)=>index !== 1)
console.log("extra: using filter (will return a array copy)",copyArr)

Validate if object has string

I have this array
switched = {"Restaurant":1,"Hotel":2,"Beauty shop":3,"Physiotherapist":4,"Dentist":5,"Bar":6,"Coffee shop":7}
and this object
result = [{"Google Place URL":"http://www.restaurant.com","Business Type":"Restaurant"},{"Google Place URL":"http://www.hotel.com","Business Type":"Hotel"}]
I want to validate if every item of the result contains words of switched
also, I'm already working with a for that returns each item separately
item[csvBusinessType] = Restaurant
how can I validate if item[csvBusinessType] is included in switched?
I have tried with
let n = switched.includes(item[csvBusinessType]);
but I get Uncaught TypeError: switched.includes is not a function
There is not good native method for this. Better to use lodash library https://www.npmjs.com/package/lodash
Here is an example
const _ = require('lodash');
console.log( _.includes(switched, item[csvBusinessType]));
I converted the object to string and used includes, I don't know if it will be the best way, but I think it is the most supported by browsers
let businessListArray = JSON.stringify(switched);
let checkBusiness = businessListArray.includes(item[csvBusinessType]);
I want to validate if every item of the result contains words of switched
If you want to validate that every item of the result object array contains words of the switched array, you should look into JS Array methods and working with Objects, just as #Andreas suggested.
In this specific case, your switched object has keys that appear to match the csvBusinessType of your item objects. This is helpful as we can use Object.keys() to grab all the keys of your switched object as an array of strings.
const businessTypes = Object.keys(switched) // = ["Restaurant","Hotel","Beauty shop","Physiotherapist","Dentist","Bar","Coffee shop"]
Now that we have grabbed the keys that you want to check against, we can use the JS Array method every() to perform a test against every object in your result object array. In this case, we will be testing that the obect's Business Type is included in our newly created businessTypes array.
const resultsValid = result.every((resultObject) => businessTypes.includes(resultObject["Business Type"]));
resultsValid is a boolean that is true if all objects in result had a Business type that matched one of the keys of your switched object.
NOTE: You may want to check Letter Casing before some of these comparisons unless you want to explicitly match only exact matches ("Beauty shop" will NOT match "Beauty Shop" for example).

How to use a index value of a dynamic array (which get filled by a click event) for filtering a new array

I'm working on a filter, which filters a array of nested arrays down to the value of one last index.
This happens in 5 steps. At each step you choose which index value (string) get used to filter the array further.
Example: You have 5 categories, each have 6 themes. Each of these 6 themes has 6 focusses(sub themes). Each focus has 6 questions. Each question has 1 answer. First you pick a categorie. This narrows the arrays down to all arrays with that categorie. Then a theme, which narrows the array down to only the arrays with that theme... etc...
So far I managed to filter down to the right question.
You can find the code here: https://github.com/okestens/vertical-filter.git
To get this work, I hardcoded the string "Deskundigheid" as a condition for the equality operator (===) that get used for the filter.
Example:
// FILTER QUESTIONS // I tried to use state.focus[0] but it does not work
let unique_questionsA = [. // now this is hardcoded
...new Set(formsA.filter((i) => i[2] === "Deskundigheid").map((i) => i[3])),
]; --------------
// FUNCTION
function displayQuestionsA() {
state.questions = [];
unique_questionsA.forEach(function (question, index) {
document.getElementById("question" + index).innerHTML = question;
state.questions.push(question);
});
------
// the state object
let state = {
category: [],
themes: [],
focus: [],
question: [],
answer: [],
};
But. What I want this filter to use is not a hardcoded string (deskundigheid) but the exact string that is visible in the div (coming from a click event which creates this filtered array and get stored in the state object). See image.
I thought: I need to track these arrays (with an object called 'state', capturing these dynamic arrays). If I then want to filter the right questions, by using the value (string) of the chosen focus (For example 'Deskundigheid', which is visible to the user), I just refer to the corresponding index value (state.focus[0]) of that chosen focus string, coming from the dynamic state object.
But, if I use the index state.focus[0] for the filter which creates the questions array, I get an empty array :(
My thought: Although the empty focus array (inside the state object), which get filled by a click event, eventually is filled with the right strings, the filter for the new array (unique_questionsA), which uses 'state.focus[0]' does not read the filled array as ‘filled’ but as empty.
I have not idea why :(
I hope I'm clear. If so, and you maybe have a clue, I would love to have a chat! Thanks O
The question can be summed up to
how do I get the text of the element when clicked, in an onclick event
listener callback function.
Your focusScript.js can be modified to
function displayQuestionsA(e) {
state.questions = [];
let unique_questionsA = [...new Set(formsA.filter((i) => i[2] === e.target.innerText).map((i) => i[3]))];
}
document.querySelector(".focus__A").addEventListener("click", displayQuestionsA);
Notice the e.target.innerText which contains the text inside the element that triggered the event(which you clicked).
if I got you correctly - both map and filter functions can give your callback second parameter - the index.
arr.map((n,i)=>{console.log(`[${i}]:${n}`)})

Search array for specific value and find its position?

I have an array and I want to search for a specific value (that I know is in the array). I just need to return the position where this value is so later I can recall it with array[2] and that value will come up.
So if the array looks like:
11292929, 199309832092, 2198829922, 938430000113
If I search the array for 2198829922 I want to call the array later and use array[2] for 2198829922 to show up.
Thank you for help!
use the indexof() method on the array.
So it would be
var indexOfItem = arr.indexOf(2198829922);

Get four unique items and add them to an array

I’m 100% certain this code has been working before. Now it strangely doesn’t.
The goal is to create a multiple choice quiz for a flashcard. I create an array to store the card's ids: the first one goes the current card id, then three other random ones. My goal is to make sure they don’t repeat either the first card or themselves.
This is how I do it:
// Array of cards’ ids to use
var randomCardsIds = [];
// Get the active card’s element id, add it to the array
randomCardsIds[0] = this.activeCardId;
// Get the current cards collection
var allCurrentCards = this.carouselEl.items.items;
// Get three random ids of other cards
var i = 0
while (i<3) {
// Get a random card element
var randomCardEl = allCurrentCards[Math.floor(Math.random() * allCurrentCards.length)];
// Get its id
var randomCardElId = randomCardEl.body.down('.card').id;
randomCardElId = randomCardElId.substring(randomCardElId.indexOf('_')+1);
console.log(randomCardElId, randomCardsIds, randomCardsIds.indexOf(randomCardElId));
// Make sure it is not in the array yet, and then add it
if (randomCardsIds.indexOf(randomCardElId) == -1) {
randomCardsIds.push(randomCardElId);
i++;
}
// Otherwise, the loop will have to run again
}
Basically, in a loop, for each item I check whether it already exists in the array or not. If it doesn’t, push it to the array, otherwise, run the loop again. Here is the console logging result:
Well, the first thing: it always shows the final state of the array: as if it is already filled with the results, which is weird. But the most important thing: the script does not recognise a duplicate (e.g. in the first result, 74 is repeated, and in the second to last, 47).
It only returns something different then -1, when it finds a match in the second position (returns 1, obviously). When a match is in a different position in the array, it always returns -1.
What am I doing wrong here?
Are you testing this in IE6? The problem is indexOf doesnot work with IE6.
For alternative you can check Best way to find if an item is in a JavaScript array?
A variation on a shuffling algoruthm seems to be the best bet here.

Categories

Resources