I have an array of latitudes and longitudes in javascript, like this:
a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)
and I would like to create a string like this:
s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."
that is, each latlon pair has a comma separating the pair, and the pairs are separated by a space.
I'm a bit stuck here (mostly because I know very little of javascript):
function polylineToKml(p)
{
var s = "";
for (var i = 0; i < p.length; i+=2)
{
var lat = p[i];
var lon = p[i+1]
// now what?
}
}
In a more functional way:
function polylineToKml(p) {
return p.map(function(el, i) {
return el + (i % 2 > 0 ? " " : ",");
}).join("").trim();
}
And if your environment supports ES6:
var polylineToKml = p =>
p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();
One way:
var s = [];
for (var i = 0; i < a.length; i+=2)
{
s.push(a[i] + "," + a[i+1]);
}
s = s.join(" ");
function polylineToKml(p) {
var s = "";
for (var i = 0, l = p.length; i < l; i += 2) {
var lat = p[i];
var lon = p[i + 1];
s += lat + ',' + lon;
// don't add a space at the end
if (i !== l - 2) s += ' ';
}
return s;
}
DEMO
one more way...
function polylineToKml(p){
var s = "";
for (var i = 0; i < p.length - 1; i++){
s += p[i] + ",";
}
s += p[p.length - 1];
return s;
}
You should adopt a proper way to organize your data set, one way is to use JSON array with key-value pairs, e.g.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}
for (var i=0; i < coordinates.length; i++){
document.getElementById("demo").innerHTML +=
coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>
In this way, the coordinates will be represented as such:
coordinates = [
{"latitude":"1.234", "longitude":"2.345"},
{"latitude":"3.456", "longitude":"5.456"},
{"latitude":"4.653", "longitude":"2.567"}
];
Find out more on http://www.w3schools.com/json/default.asp
Related
I'm trying to add elements as asterisks inside array based on number of elements. Basically If numberOfRows is 3 then I want this output:
[
' * ',
' *** ',
'*****'
]
I'm struggling on setting asterisks using the index. Can anyone point me in the right direction? Thanks a lot!
Here's my code:
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var asterisk = "*"; // Need to update this based on number of rows
for (var i = 1; i <= numberOfRows; i++) {
value += asterisk;
arr.push(value);
}
return arr;
}
Got it working! Here's a perfect solution.
function myFunction(n) {
let arr = [];
for(let f = 1; f <= n; f++) {
arr.push(' '.repeat(n - f) + '*'.repeat(f + f - 1) + ' '.repeat(n - f));
}
return arr;
}
console.log(myFunction(3));
Try something like this;
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var slots = numberOfRows * 2 - 1;
var spaceSlots, asteriskSlots, spaces;
for (var i = 0; i < numberOfRows; i++) {
asteriskSlots = i * 2 + 1;
spaceSlots = Math.floor((slots - asteriskSlots)/2);
spaces = new Array(spaceSlots).fill(' ').join('');
value = spaces + '*'.repeat(asteriskSlots) + spaces;
arr.push(value);
}
return arr;
}
console.log(myFunction(20));
I'm trying to create a simple algorithm that builds an array with a dynamic length.
Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last.
like this:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
I put together a simple demo to show what I'm trying to do.
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
Fiddle
It works fine, the only problem is it's out of order.
Right now it seems to only iterate by number of asterisks, then by index. I need it to do the opposite.
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
If someone could help that would be great because I am really at a loss!
This should get it done.
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
JSFiddle
This seems to work well:
str = "1234567"
len = str.length;
for(var stars = 1; stars < len - 1; stars++) {
for(var pos = 1; pos < len - stars; pos++) {
var s = str.substr(0, pos)
+ new Array(stars + 1).join("*")
+ str.substr(pos + stars);
document.write(s + "<br>");
}
}
New to the JavaScript language and need help creating a function which generates the following display.
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
cdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyz
.... and so on, all the way down to
xyz
yz
z
I am not asking for handouts, just a little kickstart for a beginner to get started! Links, hints, tips, anything helps! Thanks!
Arrays and loops are powerful when combined.
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
console.log(alphabet.join(''));
while (alphabet.length > 0) {
alphabet.shift();
console.log(alphabet.join(''));
}
Edit:
If you really need your decremented alphabet to be left-padded, you can use this:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var letters = alphabet.split('');
var addPadding = (function (minLength) {
return function (shortString) {
if (shortString.length < minLength) {
return new Array(
minLength - shortString.length + 1
).join(' ') + shortString;
}
};
}(alphabet.length));
console.log(alphabet);
while (letters.length > 0) {
letters.shift();
console.log(addPadding(letters.join('')));
}
Edit:
Here is a much simpler answer:
function decrementingAlphabet () {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
function iterate(spaces, letters) {
if (letters.length > 0) {
console.log(spaces + letters);
iterate(spaces + ' ', letters.substring(1));
} else {
return;
}
}
iterate('', alphabet);
}
This is simple example.
var str = '';
for (var s=0; s < 26; ++s) {
str = '';
for (var i=0; i < 26 - s; ++i) {
str += String.fromCharCode(97+s+i);
}
document.write(str + "<br/>");
}
See http://jsfiddle.net/G5Gds
Hmm, maybe this will help put you on the right track?
var str = '';
// Find out what 'a' is in ASCII
var baseLetterCode = 'a'.charCodeAt(0);
// Loop once for each letter
for (var i = 0; i < 26; ++i) {
// Append to string
str += String.fromCharCode(baseLetterCode + i);
}
In character codes, small alphabets lie from 97 onwards(97 for a). You need to use 2 for loops to print such series.
Here is your jsfiddle demo:
var display='';
for(var i=97;i<123;i++){
var s='';
for(var j=i;j<123;j++){
s+= String.fromCharCode( j );
}
display+=s;
}
alert(display);
(function() {
var theENalphabet = [];
for (var charNow = "a".charCodeAt(0); charNow <= "z".charCodeAt(0); charNow += 1) {
theENalphabet.push(String.fromCharCode(charNow));
}
var isNow = 0;
function decrAlph(startAt) {
var alphString = "";
for (var i = startAt; i < theENalphabet.length; i += 1) {
alphString += theENalphabet[i];
}
console.log(alphString);
isNow++;
while (isNow < theENalphabet.length) {
decrAlph(startAt + 1);
}
};
decrAlph(0);
})();
The charCode getting could be abstracted into a function:
var getCharCode = function(el){
return String.prototype.charCodeAt.call(el, 0);
};
getCharCode("a"); // returns 97..
In Javascript, I have a matrix with a variable number of rows and columns, which I wish to store in a multi-dimensional array.
The problem is that I need extra 3 columns and 3 extra rows with negative indexes in the matrix too. So the result for a 10x10 matrix should be a 13x13 array with indexes from -3 to 9.
I define the array with:
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = [];
for (var x = -3; x < numberofcolumns; x++) {
matrix[x] = [];
}
Is this the right way to do this? Or is there a better way?
While you can create attributes that are negative numbers, you lose some of Javascript's pseudo-array magic. In particular, matrix.length will still be 10 even though it has 13 elements. And the code in general may be surprising to anyone reading it.
You might be better off defining an offset to get the value you need out of the array index and vice-versa:
var offset = 3
for (var x=-3; x<numberofcolumns; x++) {
matrix[x+offset] = []
}
You could define the matrix as an object instead. You would lose some array functionality but you could still access matrix[-3] for example.
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = {};
for (var x = -3; x < numberofcolumns; x++) {
matrix[x] = [];
}
for (x in matrix) {
console.log(matrix[x]);
}
Or you could define your own class starting as an object or array and work from there. Here's something to get you started:
function Matrix() { };
Matrix.prototype.LBound = function()
{
var n;
for (i in this) {
if (!isNaN(i) && (isNaN(n) || n > i))
n = parseInt(i);
}
return n;
};
Matrix.prototype.UBound = function()
{
var n;
for (i in this) {
if (!isNaN(i) && (isNaN(n) || n < i))
n = parseInt(i);
}
return n;
};
Matrix.prototype.length = function()
{
var length = this.UBound() - this.LBound();
return isNaN(length) ? 0 : length+1;
};
Matrix.prototype.forEach = function(callback, indexes)
{
if (!indexes) var indexes = [];
for (var i = this.LBound(); i <= this.UBound() ; i++)
{
indexes[Math.max(indexes.length-1, 0)] = i;
callback(this[i], indexes);
if (this[i] instanceof Matrix)
{
var subIndexes = indexes.slice();
subIndexes.push("");
this[i].forEach(callback, subIndexes);
}
}
};
Matrix.prototype.val = function(newVal)
{
if (newVal)
{
this.value = newVal;
return this;
}
else
{
return this.value;
}
};
Then you'd create your matrix as such
var numberofcolumns = 10;
var numberofrows = 10;
var matrix = new Matrix();
for (var i = -3; i < numberofcolumns; i++) {
matrix[i] = new Matrix();
for (var j = -4; j < numberofrows; j++) {
matrix[i][j] = new Matrix();
matrix[i][j].val("test " + i + " " + j);
}
}
And you can run some cool functions on it
console.log("Upper bound: " + matrix.LBound());
console.log("Lower bound: " + matrix.UBound());
console.log("Length: " + matrix.length());
matrix.forEach(function(item, index)
{
if (item.val())
console.log("Item " + index + " has the value \"" + item.val() + "\"");
else
console.log("Item " + index + " contains " + item.length() + " items");
});
DEMO: http://jsfiddle.net/uTVUP/
I agree with Mark Reed's points about this being a unintuitive use of Array. I think a subclass is in order. You could follow the tutorial here to subclass Array, keep the native bracket notation, and override methods like length() so they give sensible values. Subclassing would have the added advantage of making it clear to those reading your code that something besides your everyday array is going on.
i have a array like this
["5763.34", "5500.00", "5541.67", "5541.67"]
i want to count similar values and get a out put like
(1 * 5763.34) + (1 * 5500.00) + (2 * 5541.67)
any idea how to do this?
Count values:
var array = ["5763.34", "5500.00", "5541.67", "5541.67"]
var counts = {};
for (var i = 0; i < array.length; ++i) {
var val = array[i];
if (val in counts) {
counts[val]++;
} else {
counts[val] = 1;
}
}
Print them:
var strings = [];
for (var k in counts) {
strings.push('(' + counts[k] + ' * ' + k + ')');
}
alert(strings.join(' + '));
Try it here: http://jsfiddle.net/k46kL/1
do it like this
sum = 0
for(i=0; i< array.length; i++){
sum += array[i] * (i+1)
}