Javascript Parsing Array And Getting The Unique Value
Solution 1:
It's not clear whether you have an object that contains multiple arrays, or just a standard one-dimensional array for which you've given several possible examples, but assuming the latter I think this is what you're looking for:
functionsingles(array) {
var foundIndex = -1;
for(var index = 0; index < array.length; index++) {
if(array[index] === "text-success" || array[index] === "muted") {
if (foundIndex != -1) {
// we've found two, so...returnnull;
}
foundIndex = index;
}
}
if (foundIndex != -1) {
return [ array[0], array[foundIndex], array[foundIndex+1] ];
}
return"Some default value for when it wasn't found at all";
}
console.log(singles(["532","text-warning","51","text-warning","16","muted","35","text-warning","38","text-warning","106"]));
console.log(singles(["533","text-warning","51","text-warning","16","muted","35","text-success","38","text-warning","106"]));
This loops through the input array
. The first time "text-success"
or "muted"
is found its index is stored in foundIndex
.
If "text-success"
or "muted"
is found a second time we immediately return null
.
If we get to the end of the loop then we know we found "text-success"
or "muted"
either once or not at all. If it was found once we return an array of three elements included the first item in the input array, the value of "text-success"
or "muted"
, and then the item that immediately followed that text in the array.
(Note: in your example output from Array 1 you returned the value after the matched text, but in your example output from Array 4 you returned the value before the matched text. I don't know which one you really want, but you can easily modify my function to do one or the other.)
You didn't say what you wanted to return if "text-success"
or "muted"
wasn't present in the array, so I've just returned a place-holder string.
Solution 2:
If you want to test if it exists "text-success"
or "muted"
once in the array, use this function, it will return a boolean:
functionsingles(array) {
var single = false;
for (var i = 0; i < array.length; i++) {
if (array[i] === "text-success" || array[i] === "muted") {
if (single) {
returnfalse;
}
single = true;
}
}
return single;
}
If you want to return the unique value among "text-success"
or "muted"
, use the following function. It will return the unique value, or null
otherwise:
functionsingles(array) {
var single = null;
for (var i = 0; i < array.length; i++) {
if (array[i] === "text-success" || array[i] === "muted") {
if (single) {
returnnull;
}
single = array[i];
}
}
return single;
}
If you need the code of the corresponding value, use this:
functionsingles(array) {
var single = null;
for (var i = 1; i < array.length; i += 2) {
if (array[i] === "text-success" || array[i] === "muted") {
if (single) {
returnnull;
}
single = array[i - 1];
}
}
return single;
}
Post a Comment for "Javascript Parsing Array And Getting The Unique Value"