I have an array like
[test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840, test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840,test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840]
where I need to split it and find out whether the fourth key in that array of keys has NO or YES or 1. If both NO and YES exists in an array, I need to alert the user that they have both of them in it.
please let me know how to do it in JavaScript.
You can achieve this without split() also:
var array = ['test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840', 'test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840','test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840'];
var arrayStr = array.toString();
if(arrayStr.indexOf('^^^YES') !== -1 && arrayStr.indexOf('^^^NO') !== -1){
alert('You have both of them in it');
}else{
alert('You do not have both of them in it');
}
Assuming that your array contains strings
["test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840", "test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840","test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840"]
You can get the YES/NO keys by mapping the array and splitting it like this
["test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840", "test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840","test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840"].map(function(str){return str.split("^^^")[4]})
Try this
res = arr.join("").match(/NO|YES/g)
if(res.includes("YES") && res.includes("NO")){
console.log("Both present")
}
I tried and got solved
var arrayStr = myarray.toString();
var stringExists = [];
if(arrayStr.indexOf('^^^NO^^^') !== -1) {
stringExists.push('0');
}
if(arrayStr.indexOf('^^^YES^^^') !== -1) {
stringExists.push('1');
}
if (stringExists.length > 1) {
alert("Error");
return;
}
Thanks for all your support guys..
Related
I am new to react and javascript , trying to refactor my below code to fewer lines:
for (const email of processedData) {
if (validateEmail(email)) {
count++;
if (count === 100) {
break;
}
}
}
processedData is a list of emails, tried using reduce but in reduce i could not break once i have count === 100
Thanks
Array.prototype.some will run a function on your array's element until that function returns true.
Then you can do something like this :
EDIT : single line version of my first suggestion.
var processedData = ["joe#test.co.uk", "john#test.co.uk", "jack#test.com", "jane#test.com", "amy#test.com"];
var count = 0;
processedData.some(email => validateEmail(email) && (++count === 2));
function validateEmail(email) {
console.log("validateEmail " + email);
return (email.indexOf(".com") > -1);
}
At least the loop body can be compressed easily:
for(const email of processedData) {
if(validateEmail(email) && ++count === 100) break
}
It would be hard to make it even shorter. >_>
Well, if you just want to have an array with 100 items, then this could help. Apply .filter() on the data array and then slice it to 100.
processedData.filter(email => validateEmail(email)).slice(0,100)
I think... it shoud help, but probably is better way to refactor (as always)
for(const email of processedData){
if(validateEmail(email) && count != 100) count++
}
How about using below loop?
for(let i=0,count=0; i < processedData.length && count<100; i++){
count+=validateEmail(processedData[i])
}
I have an array of pages in a book. I would like to find the index of a page that I have used filter to find. I'm farming it out to a function which works, but I wonder I can't combine indexOf or findIndex or something similar with the filter?
To get a specific page, I use this code:
getPage(pageNumber: number) {
return this.pages.filter(page => page.pageNumber == pageNumber)[0];
}
Then, to delete a page I use the following:
deletePage() {
let deletedPageLocation = this.findPageIndex();
this.pages.splice(deletedPageLocation, 1);
this.pagesChanged.next(this.pages.slice());
}
findPageIndex() {
for(var i=0; i < this.pages.length; i++) {
if (this.pages[i].pageNumber == this.currentPage) {
return i;
}
}
I would like to simplify into something like:
let deletedPageLocation = this.pages.indexOf(this.pages.filter(page => page.pageNumber == pageNumber)[0]);
But I couldn't figure out a way to get it to return the value. Any suggestions?
var found = $filter('filter')($scope.pages, { pageNumberinPages: pagenumberSearching },true);
It will return you array of objects matches your search.
I hope this helps.
You can also do it by using find and indexOf. I find it much easier than using filter. Here's a code sample in terms of your question:
deletePage(item){
let deleteItem = this.pages.find(this.findIndexToUpdate, item.pageId);
let index = this.pages.indexOf(deleteItem);
if(index > -1){
this.pages.splice(index, 1);
}
}
findIndexToUpdate(item) {
console.log("this: " + this)
return item.pageId === this;
}
Plunker demo
I am filtering an array of objects using a function that looks like this
var val = 'some text value'
this.someList = this.someList.filter(containsQuery);
function containsQuery(listItem) {
return listItem.Key_One.toLowerCase().indexOf(val) > -1 ||
listItem.Key_Two.toLowerCase().indexOf(val) > -1 ||
listItem.Key_Three.toLowerCase().indexOf(val) > -1
}
My question is what is a better way of filtering on each of the list item key values without having to write a new line for each one? i.e so I can avoid going
listItem.Key_Four.toLowerCase().indexOf(val) > -1
listItem.Key_Five.toLowerCase().indexOf(val) > -1
etc..
Any advice would be great.
Thanks!
You could use get keys of the object with Object.keys and iterate with Array#some.
function containsQuery(listItem) {
return Object.keys(listItem).some(function (k) {
return listItem[k].toLowerCase().indexOf(val) > -1;
});
}
Just a suggestion, array containing all the keys and loop them?
Like
var keys = ['key_one', 'key_two', 'key_three', 'key_four'];
for (i=0; i<keys.length; i++){
if (listItem[keys[i]].toLowerCase().indexOf(val) > -1) return true;
}
return false;
Ah damn, same idea as above, just took too long writing :D
var myStringArray = ["abcd", "efgh", "ijkl"], foundResult = false;
myStringArray.forEach(function(currentString) {
if (/\d+/.test(currentString)) {
console.log("Number found");
foundResult = true;
}
});
if(foundResult === false) {
console.log("Number NOT found");
}
This piece of code is to demonstrate the problem. I have to use an extra variable to check whether there was a match or not. Is there any elegant way to handle this without the variable?
Edit: I know I can use some, but I would like to match the no match case as well as seen in the code's last if condition.
Use some method:
if(["abcd", "efgh", "ijkl"].some(function(i){return /\d+/.test(i)})){
// if matched
} else {
// handle no match
}
An alternative that uses forEach is:
var a = ['abcd', 'efgh', 'ijkl'];
var r;
if (a.forEach(function(a){r = r || /\d/.test(a)}) || r) {
alert('found a number');
} else if (r === false) {
alert('no numbers');
}
but likely any UA that supports forEach will also support some, and some is also probably more efficient as it will stop at the first result of true.
I would like to check if a textfield, newTeamName is already in a list of teamnames stored in a select box. Unfortunately, my code does not work - what's wrong with it? Oh and I have no console problems.
optionList = [];
$('#chooseTeam option').each(function() {
optionList.push($(this).val())
});
if (form.newTeamName.value in optionList) {
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
Small Update:
Oh and my form.name.value's work fine as they work for other if statements.
optionList is an array in used for object properties(or numeric array indices), you can use indexOf to test if a value is in an array
optionList = [];
$('#chooseTeam option').each(function() {
optionList.push($(this).val())
});
if (optionList.indexOf(form.newTeamName.value) > -1) {
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
Fixed it.
$('#chooseTeam option').each(function() {
if (form.newTeamName.value == $(this).val()){
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
});
try something like this
my_array = Array();
//To find if a value or element exists in an array
if (my_array.indexOf(‘find_this_value’) != -1)
{
alert(‘Value exists in array.’);
}
//To find if a value or element DOES NOT exist in an array
if (my_array.indexOf(‘find_this_value’) == -1)
{
alert(‘Value does not exist in array.’);
}