0

I am using underscore.js on my front-end and I want to remove a pair of values from a two-dimensional array. What am I doing wrong, because the below doesn't work?

How I add the element to array:

google.maps.event.addListener(map, 'click', function (event) {
  var latitude = event.latLng.lat()
  var longitude = event.latLng.lng()
  coordinatesForMarker.push([latitude, longitude])

How I am trying to remove:

google.maps.event.addListener(marker, 'click', function (event) {                                                
  var latitude = event.latLng.lat()
  var longitude = event.latLng.lng()
  var newArray = _.without(coordinatesForMarker, ([latitude, longitude]))

Is there another solution, one not requiring a library?

2
  • Are you actually assigning newArray to coordinatesForMarker? Commented May 13, 2017 at 8:47
  • No, I am trying to assign the updated array to newArray. Commented May 13, 2017 at 8:49

3 Answers 3

1

Let's try with findWhere

var arr = [[
  1,2
], [
  3,
  3
], [
  5,
  6
]];

//substract third
arr = _.without(arr, _.findWhere(arr, [5, 6]));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

1

Is there another solution, one not requiring a library?

Absolutely! You can achieve this without a library by using native array method filter. It takes a function as an argument which returns true if you'd like to keep the element, and false if you'd like to exclude it.

var coordinatesForMarker = [[41.482583, -82.687353], [52.986944, -1.882778], [35.706336, 139.753277]];

var latitude = 52.986944;
var longitude = -1.882778;

var newArray = coordinatesForMarker.filter(function (coord) {
  return coord[0] !== latitude && coord[1] !== longitude;
});

console.log(newArray)

Comments

0

Since your array contains references of arrays the comparison isn't that easy, but let me explain that in a more detailed way.

For example you have that Array:

myArray = [ [ 21, 222 ], [ 214, 314 ] ]

The array actually just contain the references to their array so the "internal" array looks something like this:

myArray = [ arrc@0x212414 , arrc@0x253211 ]

and if you now try to compare an array which you parsed into the without function of underscore, the library just compares those references if they are equally.

So a better better way to solve your problem might be to filter the array and define an own function on how to correctly compare those arrays!

newArray = myArray.filter((element) => { element[0] !== event.lang && element[1] !== event.long })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.