Checking if a string matches a value in an array - javascript

I really need your help,
I would like to be able to check and see if a variable matches an array value and return true if it does.
ie.
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
alert("true")
I was thinking of using this approach, but for the life of me, I cannot get it to return true, ideas?
function test() {
var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
if ( $.inArray('ASFA', arr) > -1 ) {
alert("true")
}
}

Try as follows
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
array.forEach(function(ele){
console.log(ele.includes(x));
})

Quick and easy with ES6 :
let x = "ASFA",
array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"],
found = array.some(elem => elem.includes(x))
console.log(found)

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

DateFNS closestIndexTo returns NaN

I need to get the closest date from an array of dates with DateFNS v.2.0.1 closestIndexTo. I'm currently getting NaN returned. What am I missing here?
(val = 2019-09-01)
(arrDates = 2019-09-01,2019-09-03,2019-09-03,2019-09-04,2019-09-05,2019-09-05,2019-09-23,2019-10-01,2019-11-18)
getClosestToDate(val,arr) {
var arrDates = [_.map(arr, 'date')]
var closestDate = closestIndexTo(parseISO(val), arrDates)
return closestDate
},
So basically dates should be strings in first place. Next probably incorrect place is where you use [_.map(arr, 'date')] which actually place result of map into array making it double array. Also in order to parse arr into Date objects you need map arr values to parseISO function. So following code should work
var closestIndexTo = require('date-fns/closestIndexTo')
var parseISO = require('date-fns/parseISO')
var _ = require('lodash')
val = "2019-10-04"
arrDates = ["2019-09-01","2019-09-03","2019-09-03","2019-09-04","2019-09-05","2019-09-05","2019-09-23","2019-10-01","2019-11-18"]
function getClosestToDate(val, arr) {
var arrDates = _.map(arr, (a) => parseISO(a))
var closestDate = closestIndexTo(parseISO(val), arrDates)
return closestDate
}
console.log("result", getClosestToDate(val, arrDates))
Here is link to repl

Javascript Same object in array . Get the number of same attributes

I'm trying to get the number of isUnicorn === false.
isUnicorn is an attribute of Poneys Object.
Better to see the code...
const {Poney} = require("./Poneys");
class Deadpool {
constructor(){
const poneys1 =new Poney();
const poneys2 =new Poney();
const poneys3 =new Poney();
const poneys4 =new Poney();
this.Ranch={
"poney1" : poneys1,
"poney2" : poneys2,
"poney3" : poneys3,
"poney4" : poneys4,
};
So how can I know how many of my poneys are not a unicorn?
I can get if they're is a poneys or a unicorn in my ranch but not the numbers...
Thanks in advance.
Object.keys(this.Ranch).filter( (key) => !this.Ranch[key].isUnicorn) ).length;
This should do it:
var numberOfNonUnicorns =
Object.keys(this.Ranch)
.map(key => this.Ranch[key])
.filter(poney => !poney.isUnicorn)
.length;
You should iterate on your object Ranch and check for each poneys their isUnicorn property.
Something like:
let wadeWilson = new Deadpool();
let unicornsNumber = 0;
for (var key in wadeWilson.Ranch) {
if (wadeWilson.Ranch[key].isUnicorn) unicornsNumber += 1;
}

Add items to an array skipping duplicates

I want to add items to an array skipping the duplicates. However for some reason only one item is being added and the second item is not being added. Here is my code.
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = []
var from
function findMessages(messageList) {
return messageList = from;
}
add.map(function(map){
from = map
if(main_messages.find(findMessages) === undefined){
main_messages.push(map)
}
});
console.log(main_messages)
So the expected output should be
['email1#gmail.com', 'email2#gmail.com']
But the output I'm getting in this code is only
['email1#gmail.com']
What am I doing wrong and how can I fix this problem?
Looks like you're missing a = in your return statement of findMessages, so you're basically setting from to messageList instead of comparing. Here's the fixed code
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = []
var from
function findMessages(messageList) {
return messageList === from;
}
add.map(function(map){
from = map
if(main_messages.find(findMessages) === undefined){
main_messages.push(map)
}
});
console.log(main_messages)
Consider using the JavaScript 1.6 / ECMAScript 5 native filter method of an Array in the following way:
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = add.filter(function(v, i, a) {return a.indexOf(v) === i;});
Another solution that should offer better performance O(x) would be to use array.reduce:
main_messages = Object.keys(add.reduce(function (p,c) {return (p[c] = true,p);},{}));
Both solutions will result in messages containing:
["email1#gmail.com", "email2#gmail.com"]
In case you need support for Browsers that don't have this implemented, as always there is a pollyfill offered by Mozilla (see bottom of page)
i think your error in below code
function findMessages(messageList) {
return messageList = from;
}
here i think you return to its parent so it is showing one vale.
for this you need to store messageList = from in a var, then return that variable.
var x = messageList;
return x;
You could implement a uniq function. Which is a specialised form of filter.
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = uniq(add);
function uniq(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
}
console.log(main_messages)
On the other hand, map will always return an array of the same size, unless of course you muck about with assignments, etc.
map passes each element of an array to a callback function you use to modify the individual element without touching the actual array.
Think of it as 1 in 1 out, and so on, but you get the chance to change what is in the array, not how many things are in there. The idea is that there that the array resulting from map has the same length of the input array, but different content.
Methods that can result in an array of different size are filter and reduce for instance.
So being super-terse you could also do this:
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = add.filter( (el, idx, input) => input.indexOf(el) === idx );
console.log(main_messages)
You can use indexOf function in order to check the duplicate. You can try below way to add items to your array without duplicates.
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = []
add.map(function(map){
if(main_messages.indexOf(map) == -1){
main_messages.push(map)
}
});
console.log(main_messages);
Here is an easy answer: https://stackoverflow.com/a/18328062/5228251
Why do it the hard way, it can be done more easily using javascript filter function which is specifically for this kind of operations:
var add = ['email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
var main_messages = []
main_messages = add.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
});
------------------------
Output: ['email1#gmail.com', 'email2#gmail.com']
Depending on your needs, using a Set instead of an array may be what you are looking for:
The Set object lets you store unique values of any type, whether
primitive values or object references.
var add = ['email1#gmail.com', 'email1#gmail.com', 'email2#gmail.com', 'email1#gmail.com'];
// Init from an iterable.
var main_messages = new Set(add);
// Add a new email (not previously in the set).
main_messages.add('email3#gmail.com');
// Try to add an existing email, does nothing.
main_messages.add('email1#gmail.com');
console.log('main_messages:')
main_messages.forEach(msg => console.log('-', msg));
Of course, this option is only viable if you keep the data stored in the Set. It would be quite inefficient to convert it into an array after each insertion.
Set is an ES2015 feature. You may want to check the compatibility table and consider using a polyfill if needed.

Is there a preferred way of converting a SqlResultsetRowList to an array?

When I try this in Ramda I get an Illegal Invocation exception:
var arr = R.map(r.rows.item, R.range(0, r.rows.length));
I can do it in two lines but then it seems even more of a hack:
var i = 0;
var arr = R.repeatN(null, r.rows.length).map( function() { return r.rows.item(i++); } );
What is the preferred method of accomplishing this? Should I stick with a loop instead?
this should do it:
var rowArray = R.map.idx(function(row, i) { return r.rows.item(i); }, r.rows);
That should map each row object into the output array rowArray.

Categories