I have an array in the following format:
let initialDataset=
[
[3.6216,8.6661,-2.8073,-0.44699,1 ],
[4.5459,8.1674,-2.4586,-1.4621,0 ],
[3.866,-2.6383,1.9242,0.10645,1 ],
[3.4566,9.5228,-4.0112,-3.5944,0 ],
[0.32924,-4.4552,4.5718,-0.9888,0 ],
//and so on...
Goal: Seperate last column/element from each array inside 'initialDataset' variable and put them into a distinct array. They have to be in the same index too. Such as:
let initialDataset=
[
[3.6216,8.6661,-2.8073,-0.44699],
[4.5459,8.1674,-2.4586,-1.4621],
[3.866,-2.6383,1.9242,0.10645],
[3.4566,9.5228,-4.0112,-3.5944],
[0.32924,-4.4552,4.5718,-0.9888],
let division=[1,0,1,0,0];
To accomplish this, i used following piece of code:
let division=[];
for(i=0;i<initialDataset.length;i++){
division[i]=initialDataset[i].pop();
}
It gets the work done but i didn't quite like it. Looking for a better way to achieve it. Any suggestions in terms of optimization and code quality wise ? Thanks in advance.
You could map the popped value.
var data = [[3.6216, 8.6661, -2.8073, -0.44699, 1], [4.5459, 8.1674, -2.4586, -1.4621, 0], [3.866, -2.6383, 1.9242, 0.10645, 1], [3.4566, 9.5228, -4.0112, -3.5944, 0], [0.32924, -4.4552, 4.5718, -0.9888, 0]],
division = data.map(a => a.pop());
console.log(division);
Functional answer using a handy, reusable last function. This method does not mutate the input array.
const data = [[3.6216,8.6661,-2.8073,-0.44699,1],[4.5459,8.1674,-2.4586,-1.4621,0],[3.866,-2.6383,1.9242,0.10645,1],[3.4566,9.5228,-4.0112,-3.5944,0],[0.32924,-4.4552,4.5718,-0.9888,0]]
const last = array => {
const { length } = array
return length > 0 ? array[length - 1] : undefined
}
const division = data.map(last)
console.log(division)
Related
I need to have in array with lat/lon points like that:
/*
var polylinePoints = [
[37.781814, -122.404740],
[37.781719, -122.404637],
[37.781489, -122.404949],
[37.780704, -122.403945],
[37.780012, -122.404827]
];
*/
But I need first to sort it by third parameter which is timestamp?
How to do that? I know how to do that in PHP but not in JS
var polylineTimestamp = [
[37.781814, -122.404740, 1666543938],
[37.781719, -122.404637, 1666543938],
[37.781489, -122.404949, 1666543938],
[37.780704, -122.403945, 1666543938],
[37.780012, -122.404827, 1666543938]
];
Then I need to delete (trim) sorted array (delete timestamp) to have something like polylinePoints.
Here is Jsfiddle:
https://jsfiddle.net/qsdaLz7h/
Array .sort() and .map() will get you there. You could combine them, but it'll be easier for you to follow the logic when they're separated, as below.
// I changed your original timestamps to give some difference
var polylineTimestamp = [
[37.781814, -122.404740, 1666543958],
[37.781719, -122.404637, 1666543948],
[37.781489, -122.404949, 1666543968],
[37.780704, -122.403945, 1666543938],
[37.780012, -122.404827, 1666543998]
];
// sort polylineTimestamp by third parameter (timestamp) older first
var sortedarray = polylineTimestamp.sort((a,b)=> {
return a[2] - b[2];
});
// Remove timestamp from resulting array
var polylinePoints = sortedarray.map(el => {
return [el[0],el[1]];
});
// Log to console
console.log(polylinePoints)
u can make a temp var
let arr = []
polylineTimestamp.forEach((el) => {
arr.push([el[0],el[1]])
})
console.log(arr)
//! expected output would be
arr = [
[ 37.781814, -122.40474 ],
[ 37.781719, -122.404637 ],
[ 37.781489, -122.404949 ],
[ 37.780704, -122.403945 ],
[ 37.780012, -122.404827 ]
]
you also can get a new arr the it can filter to not get the index 2 from the origin arr
Here is your answerer:
const TIMESTAMP_POSITION = 2
var polylineTimestamp = [
[37.781814, -122.404740, 1666540000],
[37.781719, -122.404637, 1666541000],
[37.781489, -122.404949, 1666542000],
[37.780704, -122.403945, 1666543000],
[37.780012, -122.404827, 1666544000]
];
polylineTimestamp.sort(function (a, b) {
// Turn your timestamp number into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b[TIMESTAMP_POSITION]) - new Date(a[TIMESTAMP_POSITION]);
})
//map to remove timestamp
var polyLineArray = polylineTimestamp.map(function (polyLine) {
return [polyLine[0], polyLine[1]]
})
I used the sort function to sort your initial array using date conversion from timestamp.
when just mapping the array to remove the timestamp
I have the following List of strings:
books = ['alpha', 'betta', 'other']
and the following List of Dict:
guide = [
{'name':'alpha', 'id':'1'},
{'name':'betta', 'id':'2'},
{'name':'other', 'id':'3'},
...
...
]
I receive a list of books as an input from API call, and now i need to map the book name to its corresponding id (for something I need it).
For example, if I get "betta" as in input, I need to get its id which is "2" in this case in order to use it somewhere else.
What is the best practice to do so? Is there a mapper or something similar that can help?
I know I can do this by creating 2 For loops and compare the input string (betta) with the element['name'] for each element in guide, but the guide I have is really big and i will need to loop through a bunch of data.
Any help would be appreciated! Thank you!
What I would suggest you to do is the following
const guide = new Map([
["alpha", 1],
["betta", 2],
["other", 3]
]);
console.log(guide.get('betta')); // 2
This is the best approach for performance and it is also more readable and less resource consuming.
EDIT:
benchmark loop vs map, and the gap is bigger with bigger collection
Turn the array of objects into a mapping of names to IDs first.
const guide = [ {'name':'alpha', 'id':'1'}, {'name':'betta', 'id':'2'}, {'name':'other', 'id':'3'}];
const idsByName = Object.fromEntries(guide.map(({ name, id }) => [name, id]));
console.log(idsByName['alpha']);
I like the answers already provided by #CertainPerformance and #AdrienDePeretti.
Here's another approach. I wonder which performs best!
const guide = [ {'name':'alpha', 'id':'1'}, {'name':'betta', 'id':'2'}, {'name':'other', 'id':'3'}];
const obj = guide.reduce((acc,{name,id}) => ({...acc,[name]:id}),{});
console.log(obj['betta']);
There is a find method in JS for this purpose:
const guide = [ {'name':'alpha', 'id':'1'}, {'name':'betta', 'id':'2'}, {'name':'other', 'id':'3'}];
const idsByName = (targetName) =>
guide.find(({ name }) => name === targetName)?.id;
console.log(idsByName('betta'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Good day! I badly need help for this one, I have an array with many elements/data that is needed to be display in textbox. Each array element/data must be inside the textbox. (The Textbox must be dynamically set up using loop with the array data inside it)
arr = ["1"-"2"-"3"-"4"-"5"]; //my array is from the db, this is example only
conv_arr = arr.split("-")
var myArray = [conv_arr];
var ArrayInText = document.createElement('input');
myArray.forEach(function(conv_arr) {
ArrayInText.value = conv_arr ;
document.body.appendChild(ArrayInText);
It displays the array (pretend this is a textbox [ ])
[ 1, 2, 3, 4, 5 ]
I want a result that looks like this (One textbox per element using loop)
[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]
You can see the demo here=> https://jsfiddle.net/4ow6k8j5/1/
After removing unnecessary assignments, you can use below simplest solution;
conv_arr = arr.split("-")
conv_arr.forEach(function(elem) {
var ArrayInText = document.createElement('input');
ArrayInText.value = elem ;
document.body.appendChild(ArrayInText);
});
[{…}]
0: {productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}
length: 1
__proto__: Array(0)
Hello, This is my console output from sorting 18 sets of information like this. I have successfully sorted the list to just the entry above. now I want to store each set of information into its own variable. This is in Javascript
The Variable above is sortedList
Can someone help me make code to pull each bit of information out as a new variable?
I tried
finalProduct = sortedList.productName
finalTravelSpeed = sortedlist.travelSpeed
finalMaterialThickness= sortedList.materialThickness
finalProcess = sortedlist.process
You only make some little typos: you wrote in some cases sortedlist instead of sortedList, you didn't use camelCase-writing and you forgot the ";" and the line-end.
Because your sorted list is an array and you want the first element of it you allways have to take the first element sortedList[0] and not sortedList.
let sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
finalProduct = sortedList[0].productName;
finalTravelSpeed = sortedList[0].travelSpeed;
finalMaterialThickness= sortedList[0].materialThickness;
finalProcess = sortedList[0].process;
console.log (finalProduct, finalTravelSpeed, finalMaterialThickness, finalProcess);
From what i understood this is an array of objects of length 1, so first you should access index 0 of that array to get that object:
let finalProduct = sortedList[0].productName
let finalTravelSpeed = sortedlist[0].travelSpeed
let finalMaterialThickness= sortedList[0].materialThickness
let finalProcess = sortedlist[0].process
as far as i understood ! you want method to pulling
data from arrays or objects and put this data in dynamic variables have same name
var sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
// this function for extract objects to variables worked dynamically
function extractor_Object(obj = {}){
for(let i in obj) window[i] = obj[i];
}
extractor_Object(sortedList[0]);
console.log(productName , travelSpeed , materialThickness , process);
i hope this function help you
So to GET an output like this, I had to use some pretty cool tricks (see Analyzing Data from JSON in JavaScript). Please note my data in this example (# rows) is different.
var feeds = [].concat.apply([], dataSet_parsed.map(s => s.data));
//flattens arrays AGAIN to show all targets
var targets = [].concat.apply([], feeds.map(s => s.data));
//return target hits total
var targetList = targets.reduce(
function(prev, cur) {
var val = cur["val"];
prev[val] = ((prev[val] || 0) + 1);
return prev;
}, {});
// Output: {TargetA: 5, TargetB: 6, TargetC: 4, TargetD: 2}
Basically, I'm trying to get a count of how many times a target was seen per group. And fantastic! this works.
Here's my question. how do I display the output---
{TargetA: 5, TargetB: 6, TargetC: 4, TargetD: 2}
---in a table? There are no guarantees that I will always return the same TYPE of Targets (i.e. next load I could have:
{TargetK: 10, TargetL: 2, TargetM: 5, TargetN: 3, TargetO: 7, TargetP: 8}
I've tried using JSON.stringify and .replace() but I'm not getting very far. And even after that, I don't think I could style that output very well.
JSON.stringify(targetList).replace(/\}/g,'').replace(/\{/g,'')