Changing specific array value in javascript - javascript

let bdays = ["10-17", "05-19", "20-19"];
how do i change the '-' in that array to '/'.

You could also use Array.map to create a new array of formatted values
let bdays = ["10-17", "05-19", "20-19"];``
let formattedBdays = bdays.map((date) => {
return date.replace('-','/')
});
console.log(formattedBdays);
Gives Output
['10/17', '05/19', '20/19']
You can learn more about map in the docs here

let bdays = ["10-17", "05-19", "20-19"];``
for( let bday of bdays) {
bdays[bdays.indexOf(bday)]= bday.replace('-','/');
}

Related

Javascript - Adding new element to array using for loop

I'm trying to convert url. Using for loop to extract Acura, Audi. Here what I got so far:
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
makes.push(make);
console.log(makes)
}
};
The result is
[ 'Acura' ]
[ 'Acura', 'Audi' ]
As you see it has one more array. Is there a way to get only [ 'Acura', 'Audi' ]?
FYI there's a native solution for getting values a from query string, check URLSearchParams
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const makes = new URLSearchParams(newSrpParams).getAll('make');
console.log(makes);
That is happening because you are logging the array inside the for loop. If you move it outside you will get
['Acura', 'Audi']
The Code:
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
console.log(newSrpParamsArray)
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
console.log(make)
makes.push(make);
}
};
console.log(makes) // The change
You were consoling the results inside the if statement it will run two times. So as a result make[] array print two times. That's why you get the two arrays.
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
makes.push(make);
}
};
console.log(makes)
Make sure to console make[] from outside of the for a loop. That's only. I couldn't see any other wrong line in your code.
Why not use URLSearchParams?
and you can replace the URL with window.location.href
let url = new URL(`http://localhost?year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000`)
let params = new URLSearchParams(url.search).getAll("make")
console.log(params)

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

Array with key value string into Object JavaScript

I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}

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;
}

Categories