Setting the array status based on the object status in the array - javascript

I have an Array of Objects and each object has a status property,It may be pass or Fail or Skipped.If the Object status is other than 'pass', then i have to set the array status has fail irrespective of the number of objects in array and irrespective object with status pass.
singleTestMethod=[
{'status':'PASS'},
{'status':'PASS'},
{'status':'FAIL'},
{'status':'SKIPPED'},
'arrayStatus':'']
i expect the array status should only be set to pass when all the object status in the array are pass otherwise it should be set to fail only.

As what I understand, you want to know if all the objects has a status of pass, else it is considered fail right?
Then:
const testArr1 = [
{status:'PASS'},
{status:'PASS'},
{status:'FAIL'},
{status:'SKIPPED'},
{arrayStatus:''}]
const testArr2 = [
{status:'PASS'},
{status:'PASS'}]
const checkArray = (testArr) => !testArr.find(each => each.status !== 'PASS')
console.log(checkArray(testArr1)) // false
console.log(checkArray(testArr2)) // true

I think that you made a typo in writing your array, I took the freedom to fix it.
Because of a lack of clarity in your request I also assume that your structure will always be identical so 'arrayStatus' will be the last item of the array.
What I understood is that you want to check all the 'status' values in the array.
If all are 'PASS' then 'arrayStatus' must become 'PASS' too, otherwise 'arrayStatus' must become 'FAIL'.
If the above assumptions are right please try the following code:
var singleTestMethod=[
{'status':'PASS'},
{'status':'PASS'},
{'status':'FAIL'},
{'status':'SKIPPED'},
{'arrayStatus':''}];
console.log("singleTestMethod array before its check:")
console.log(singleTestMethod);
function setArrayStatus(myArray){
var totalItems = myArray.length - 1;
var totalPass = 0;
myArray.forEach(function(entry) {
if (entry.status === "PASS"){
totalPass++;
}
});
if (totalItems === totalPass){
myArray[myArray.length - 1] = {'arrayStatus': 'PASS'};
} else {
myArray[myArray.length - 1] = {'arrayStatus': 'FAIL'};
}
return myArray;
}
singleTestMethod = setArrayStatus(singleTestMethod);
console.log("singleTestMethod array after its check:")
console.log(singleTestMethod);

Thanks for your answers,i have tried it using the object filter property has follows..
var singleTestMethod = [
{'status':'PASS'},
{'status':'FAIL'},
{'status':'SKIPPED'},
{'arrayStatus':''}];
const result = singleTestMethod.filter(singleTestMethod =>
singleTestMethod.status === 'FAIL' || singleTestMethod.status === 'SKIPPED');
console.log(result);
if(result.length == 0){
singleTestMethod.arrayStatus = 'PASS';
}else{
singleTestMethod.arrayStatus = 'FAIL';
}
console.log( singleTestMethod.arrayStatus);

Related

Define variable status by priority

I have a situation here.
I want to define a search status based on some priorities.
this are the possible status: notGenerated, generated, processing, invalidInput
I have a array like this:
['notGenerated', 'generated', 'generated', 'processing', 'invalidInput']
the priority is, if some element on array has 'notGenerated' the search status is 'notGenerated'
for the search status be 'generated', the elements on array cant be 'processing' or 'notGenerated', and need to has 'generated' in some of them.
for the search status be 'processing', some element on array must be 'processing' and the elements on array cant be 'notGenerated'.
for the 'invalidInput', we need that every element on the array be 'invalidInput'.
I make this code but i think its very ugly, how can i improve it?
resultsStatus = ['someStatus', 'someStatus', 'someStatus']
let searchStatus;
const hasNotGenerated = resultsStatus.includes('notGenerated');
const hasProcessing = resultsStatus.includes('processing');
const hasGenerated = resultsStatus.includes('generated');
const allInvalidInput = resultsStatus.filter((result) => result.status === 'invalidInput');
if (hasNotGenerated) searchStatus = 'notGenerated';
if (hasGenerated && !hasProcessing) searchStatus = 'generated';
if (resultsStatus.length === allInvalidInput.length) searchStatus = 'invalidInput';
return searchStatus;
You can just define "exit points" from your function, as soon as a criterion is satisfied.
Additionally, it's preferable to use an enum, as it guarantees no typos or other inconsistencies in your statuses.
const Status = {
NOT_GENERATED: 'notGenerated',
GENERATED: 'generated',
PROCESSING: 'processing',
INVALID: 'invalidInput',
};
function determineStatus(arr) {
if (arr.includes(Status.NOT_GENERATED)) return Status.NOT_GENERATED;
// If the array included 'notGenerated', it'd be returned on the previous check
if (arr.includes(Status.PROCESSING)) return Status.PROCESSING;
// If the array included 'notGenerated' or 'processing', it'd be returned on the previous checks
if (arr.includes(Status.GENERATED)) return Status.GENERATED;
if (arr.every(element => element === Status.INVALID)) return Status.INVALID;
}

Javascript Equalize Element From Array

Guys I want to get an element from array. Here:
Follower:
{ follower:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
user id:
5edfe92fbfc9d677005d55cc
The process:
if(follower == user){
console.log("sdasdsad")
}else{
console.log("no")
}
But when I do it it always returns as no.
Also this is the codes of===> Nodejs Follow System Not Working Properly
It is a nodejs project. So please look at the above link.
When I do
if(follower.includes(user)){
It gives the error of:
TypeError: Cannot read property 'includes' of null
And when I try to change some I get this error:
TypeError: takip.includes is not a function
Guys so thats why I say please look at the above code.
So how to equalize them?
As other peoples said earlier the follower itself is a property which its value is an array itself, so if you want to check whether an item exists within it or not you can check it with includes(), if it exists it will return true otherwise it will return false.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if (follow.follower.includes(user)) {
console.log("sdasdsad")
} else {
console.log("no")
}
But if you looking to find the exact position of the item within that array you can find it with indexOf(). If the item does not exist within the array it will return -1, otherwise, it will return the index of that item within the array.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
console.log(follow.follower.indexOf(user));
You are trying to compare a string to an array so it will never pass the if statement.
If you change your if to be if ( follower.includes(user)) { then it will search the array for the string.
var follower = [
'5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
var user = '5edfe92fbfc9d677005d55cc'
// This will always fail as follower is an array not a string
if (follower.includes(user)){
console.log("sdasdsad")
} else {
console.log("no")
}
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Looks like follower is a property. You can use this solution:
objectName.follower.forEach(item =>
if (item == user) console.log(`${item} is the answer`);
);
This way, javascript will go through all of the elements in the array and print it out if it is matching with your user variable.
You can also use for loop or while loop for the same process, however, since you're using an array, forEach will be much more useful.
If this was not your question and I misunderstood your question, let me know, I'll see if I can help.
I hope this helps
var obj = {
follower: [ '5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
};
var userId = '5edfe92fbfc9d677005d55cc';
function searchUser(object, user){
if(obj.follower.includes(user)){
return object.follower.filter(x => x == user);
} else {
return 'no';
}
};
console.log(searchUser(obj, userId));
You can use Array.protorype.some() to check if user exists in the follower array.
const obj = {
follower: [
"5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if(obj.follower.some(item => item === user)) {
console.log("found")
} else{
console.log("no")
}
You can also get the item with Array.protorype.find() with the same way as above, just assign it to a variable
Array.prototype.some
Array.prototype.find

Steam API, different json format

Recently i integrated CSGO stats in my discord bot, but today i saw that for almost every player the API sends a different json data.
Here 2 examples:
https://jsonblob.com/58688d30-26d0-11e8-b426-7b3214778399
https://jsonblob.com/52ed0c3f-26d0-11e8-b426-43058df4a5a6
My question was how to request the data properly so a win is really a win and not a kill.
.addField('**Wins:**', `${object.playerstats.stats[5].value}`, true)
.addField('**Time played:**', `${object.playerstats.stats[2].value}` + ' minutes', true)
.addField('**Kills:**', `${object.playerstats.stats[0].value}`, true)
.addField('**Deaths:**', `${object.playerstats.stats[1].value}`, true)
.addField('**Bombs planted:**',`${object.playerstats.stats[3].value}`, true)
.addField('**Money earned:**',`${object.playerstats.stats[7].value}`, true)
.addField('**Knife kills:**',`${object.playerstats.stats[9].value}`, true)
.addField('**Headshot kills:**',`${object.playerstats.stats[24].value}`, true)
.addField('**Dominations:**',`${object.playerstats.stats[39].value}`, true)
.addField('**Rounds played:**',`${object.playerstats.stats[44].value}`, true)
The name property of stats items appear to be unique enough to find. You can use array.find to look for the correct stat by name.
const stats = object.playerstats.stats
const totalKills = stats.find(s => s.name === 'total_kills').value
const totalDeaths = stats.find(s => s.name === 'total_deaths').value
Taking it further, you can use array.reduce to generate an object whose key is name and value is value for each item in the array. This way, you access it like an object.
const stats = object.playerstats.stats
const statsObj = stats.reduce((c, e) => (c[e.name] = e.value, c), {})
const totalKills = statsObj.total_kills
const totalDeaths = statsObj.total_deaths
Rather than trying to reference the array indexes, why not convert the API response into an easier-to-parse format?
// do this once...
let playerStats = {};
object.playerstats.stats.forEach(s => playerStats[s.name] = s.value);
// ...then you can use the playerStats variable however you need:
.addField('**Kills:**', `${playerStats.total_kills}`, true)
.addField('**Wins:**', `${playerStats.total_wins}`, true)
The stats array is just not sorted. you can use .find() to get the correct entry from the stats.
for example
const totalWins = object.playerstats.stats.find(stat => {
return stat.name === 'total_wins';
});
.addField('**Wins:**', `${totalWins.value}`, true)
You are approching this problem the wrong way.
JSON is not a format that is ordered. What that means is that there is no guarantee that the JSON data will return in the same order everytime. It is not a default of the API.
There is one way you could still use your way: by sorting the 'stats' array by name. but it is a long operation and not a very good idea.
The way do to this is to do a lookup by name.
For example, if you want to find the wins, you do this :
object.playerstats.stats.find(elem => elem.name === 'total_wins').value;
The find function does a lookup and returns the first element matching the predicate (elem.name === 'total_wins'). It returns null if not element matched the predicate (so be careful here).
You could do a function that returns a value for you :
findValue(statsArray, name) {
const entry = statsArray.find(elem => elem.name === name);
return entry ? entry.value : '?';
}
And then your code would look like this :
...
.addField('**Wins:**', findValue(object.playerstats.stats, 'total_wins'), true)
...
The main thing here is : never assume fields in a JSON will return the same every time. Always use lookup, and not indexes (unless it is sorted).

how to search through the array and return the matching value

I have an array of some class names that all of the values in that array end with numbers. I want to have a function that when I give it a number, it search through that array, and check the last 3 digits of each value, to find the matching number and return that matching value.
So lets say, I give it value 200 and it searches through the array and returns wi-owm-200.
I manage to make it but it does not return it. It does find the value, but when it is outside of the function, it returns 'undefined'.
Here is my code: Fiddle
var owmIcon = ["wi-owm-200", "wi-owm-201", "wi-owm-202", "wi-owm-210", "wi-owm-211", "wi-owm-212", "wi-owm-221", "wi-owm-230", "wi-owm-231", "wi-owm-232", "wi-owm-300", "wi-owm-301", "wi-owm-302", "wi-owm-310", "wi-owm-311", "wi-owm-312", "wi-owm-313", "wi-owm-314", "wi-owm-321", "wi-owm-500", "wi-owm-501", "wi-owm-502", "wi-owm-503", "wi-owm-504", "wi-owm-511", "wi-owm-520", "wi-owm-521", "wi-owm-522", "wi-owm-531", "wi-owm-600", "wi-owm-601", "wi-owm-602", "wi-owm-611", "wi-owm-612", "wi-owm-615", "wi-owm-616", "wi-owm-620", "wi-owm-621", "wi-owm-622", "wi-owm-701", "wi-owm-711", "wi-owm-721", "wi-owm-731", "wi-owm-741", "wi-owm-761", "wi-owm-762", "wi-owm-771", "wi-owm-781", "wi-owm-800", "wi-owm-801", "wi-owm-802", "wi-owm-803", "wi-owm-804", "wi-owm-900", "wi-owm-901", "wi-owm-902", "wi-owm-903", "wi-owm-904", "wi-owm-905", "wi-owm-906", "wi-owm-957"];
var res = findOWMIcon("200");
console.log(res);
function findOWMIcon(num) {
$.each(owmIcon, function(key, value) {
var classNum = value.substr(value.length - 3);
if (parseInt(num, 10) === parseInt(classNum, 10)) {
console.log(value);
return value;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Any idea how to solve it? So I can get the found value outside the function?
This is sufficient:
owmIcon.filter(e => e.slice(-3) == "200");
// Get all elements that ends in "01"
items = get_all_items().filter(e => e.slice(-2) == "01");
console.log(items);
function get_all_items(){
return ["wi-owm-200", "wi-owm-201", "wi-owm-202", "wi-owm-210", "wi-owm-211", "wi-owm-212", "wi-owm-221", "wi-owm-230", "wi-owm-231", "wi-owm-232", "wi-owm-300", "wi-owm-301", "wi-owm-302", "wi-owm-310", "wi-owm-311", "wi-owm-312", "wi-owm-313", "wi-owm-314", "wi-owm-321", "wi-owm-500", "wi-owm-501", "wi-owm-502", "wi-owm-503", "wi-owm-504", "wi-owm-511", "wi-owm-520", "wi-owm-521", "wi-owm-522", "wi-owm-531", "wi-owm-600", "wi-owm-601", "wi-owm-602", "wi-owm-611", "wi-owm-612", "wi-owm-615", "wi-owm-616", "wi-owm-620", "wi-owm-621", "wi-owm-622", "wi-owm-701", "wi-owm-711", "wi-owm-721", "wi-owm-731", "wi-owm-741", "wi-owm-761", "wi-owm-762", "wi-owm-771", "wi-owm-781", "wi-owm-800", "wi-owm-801", "wi-owm-802", "wi-owm-803", "wi-owm-804", "wi-owm-900", "wi-owm-901", "wi-owm-902", "wi-owm-903", "wi-owm-904", "wi-owm-905", "wi-owm-906", "wi-owm-957"];
}
Use function(e){ return e.slice(-3) == "200"; } instead of e => ... if you care about backward compatibility (ES5 and before).
let data = ["wi-owm-200", "wi-owm-201", "wi-owm-202", "wi-owm-210", "wi-owm-211", "wi-owm-212", "wi-owm-221", "wi-owm-230", "wi-owm-231", "wi-owm-232", "wi-owm-300", "wi-owm-301", "wi-owm-302", "wi-owm-310", "wi-owm-311", "wi-owm-312", "wi-owm-313", "wi-owm-314", "wi-owm-321", "wi-owm-500", "wi-owm-501", "wi-owm-502", "wi-owm-503", "wi-owm-504", "wi-owm-511", "wi-owm-520", "wi-owm-521", "wi-owm-522", "wi-owm-531", "wi-owm-600", "wi-owm-601", "wi-owm-602", "wi-owm-611", "wi-owm-612", "wi-owm-615", "wi-owm-616", "wi-owm-620", "wi-owm-621", "wi-owm-622", "wi-owm-701", "wi-owm-711", "wi-owm-721", "wi-owm-731", "wi-owm-741", "wi-owm-761", "wi-owm-762", "wi-owm-771", "wi-owm-781", "wi-owm-800", "wi-owm-801", "wi-owm-802", "wi-owm-803", "wi-owm-804", "wi-owm-900", "wi-owm-901", "wi-owm-902", "wi-owm-903", "wi-owm-904", "wi-owm-905", "wi-owm-906", "wi-owm-957"];
// Suppose you want to get all elements that end with 200, so...
let filteredData = data.filter(item => item.slice(-3) === "200");
console.log(filteredData);

filtering an element from object array

I have an array of object something like below
Object[0]
canUpload:false
canBeRemoved:true
type:Object
allowMultiple:false
deleted:false
key:"testValue"
Object[1]
canUpload:true
canBeRemoved:true
type:Object
allowMultiple:false
deleted:false
key:"testValue2"
I want to remove an elements from array which contains key:testValue
var myValues = this.testData.data3;
if(!this.testData.canDownload){
myValues= myValues.filter(function(value){
if(!value.canUpload)
return value.type.key==='testValue';
else return false;
});
But its not removing .Whats the right way to do it?
Here is the full code .I can see myValues array of size 2 .If i print myValues after if block its empty.
Code pen:http://codepen.io/developer301985/pen/woGBNg
If your want to filter your array on the basis of two conditions:
canUpload attr is false
type.key is equal to 'testValue'
so you may want to return false in case of canUpload is true to be as follow:
myValues= myValues.filter(function(value) {
if(!value.canUpload)
return value.type.key === 'testValue';
else return false;
});
Otherwise, you just want to filter on type.key is equal to 'testValue', so it will be as follow:
myValues= myValues.filter(function(value) {
return value.type.key === 'testValue';
});
Note, if the callback function you passed into filter returns true, the element will be kept rather than removed. So in your case, you should return false when the value is testValue.
If I understand you correctly, you want to remove item with value.canUpload==false AND type.key === 'testValue'. Then the negate is value.canUpload || value.type.key !== 'testValue'
var myValues = this.testData.data3;
if (!this.testData.canDownload) {
myValues = myValues.filter(function(value) {
return value.canUpload || value.type.key !== 'testValue';
});
}
Let me know whether it works :)

Categories

Resources