Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over arrays and objects in JavaScript [duplicate]

var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}]; 

How would I iterate through this. I want to print x and y value first, then 2nd and soo on....

like image 281
gaurav singh Avatar asked Nov 04 '16 06:11

gaurav singh


People also ask

How do you duplicate an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you remove duplicate objects from array of objects in JS?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


2 Answers

Use Array#forEach method for array iteration.

var points = [{    x: 75,    y: 25  }, {    x: 75 + 0.0046,    y: 25  }];    points.forEach(function(obj) {    console.log(obj.x, obj.y);  })
like image 109
Pranav C Balan Avatar answered Sep 18 '22 11:09

Pranav C Balan


var points = [{ x: 75, y: 25},{ x: 75+0.0046, y: 25}];    //ES5  points.forEach(function(point){ console.log("x: " + point.x + " y: " + point.y) })      //ES6  points.forEach(point=> console.log("x: " + point.x + " y: " + point.y) )
like image 40
A.T. Avatar answered Sep 22 '22 11:09

A.T.