Bangjeko
Bangjeko

Reputation: 17

How to looping index array in another array JavaScript

I have some JavaScript code like this:

<script>
  var nama_titik = ["titik1", "titik2"];
  var lat = ["-7.0732534", "-7.0737645"];
  var lon = ["110.4111171", "110.4130483"];
  var locations = [
    [nama_titik[0], lat[0], lon[0]]
  ];

  document.getElementById("demo").innerHTML = locations;
</script>

How to looping index array in location, so I did not write code like this:

var locations = [
  [nama_titik[0], lat[0], lon[0]],
  [nama_titik[1], lat[1], lon[1]],
  [nama_titik[2], lat[2], lon[2]],
];

Upvotes: 0

Views: 48

Answers (3)

Peter Seliger
Peter Seliger

Reputation: 13366

One generic approach that solves this kind of problem is, as so often, based on Array.reduce ...

var nama_titik = ["titik1", "titik2", "foo"];
var lat = ["-7.0732534", "-7.0737645", "bar"];
var lon = ["110.4111171", "110.4130483", "baz"];

var locations = [
  [ nama_titik[0], lat[0], lon[0] ],
  [ nama_titik[1], lat[1], lon[1] ]
];

console.log('Array.from(locations) ... by hand : ', Array.from(locations));

function mapFromManyLists(collector, item, idx) {
  var vector = [item];

  collector.lists.forEach(function (list) {
    vector.push(list[idx]);
  });
  collector.list.push(vector);

  return collector;
}

locations = nama_titik.reduce(mapFromManyLists, {

  lists:  [lat, lon/*, as, many, lists, as, one, needs*/],
  list:   []

}).list;

console.log('Array.from(locations) ... by generic function : ', Array.from(locations));
.as-console-wrapper { max-height: 100%!important; top: 0; }

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can use a loop for any of the array to get the values from the respective index and create array or arrays in locations variable. You can also have a check for the lengths of all three array to prevent any runtime errors.

var nama_titik = ["titik1","titik2"];
var lat = ["-7.0732534","-7.0737645"];
var lon = ["110.4111171","110.4130483"];
var locations = [];
if(nama_titik.length === lat.length && lat.length === lon.length){
  for(var i=0; i<nama_titik.length; i++){
    var tempArr = [];
    tempArr.push(nama_titik[i]);
    tempArr.push(lat[i]);
    tempArr.push(lon[i]);
    locations.push(tempArr);
  }
  console.log(locations);
  document.getElementById("demo").innerHTML = locations;
} else{
  console.log('Incorrect data');
}
<div id ='demo'></div>

Upvotes: 0

Programmer
Programmer

Reputation: 2123

If I understood well, this is what you're looking for -

var locations = [];
for (var i = 0; i < nama_titik.length; i++) {
    locations.push([ nama_titik[i], lat[i], lon[i] ])
}

Upvotes: 1

Related Questions