How to get last position of an ID in the array

Asked

Viewed 1,024 times

0

Hello, I have a function that captures coordinates of elements that I move on the screen with the mouse. But this function of mine, it takes the trace of the coordinates of the elements that I drag, I would like to take only the last coordinate of each one, to save in the bank. How I could handle the array so that I only get the last coordinate relative to the id?

Function that picks up coordinates:

 moveElem(elemID) {
    let self = this;
    function parseNumber(num) {
     return parseFloat(num.replace(/[^\d]/)) || 0;
  }

    let moveElemento = (function () {

    let coords = [];
    let startX;
    let startY;

    let currentElemento = null;
    let currentWidth = 0;
    let currentHeight = 0;
    let currentLeft = 0;
    let currentTop = 0;
    let callMoveOnElemento = null;
    let callMoveStopElemento = null;

    let contentMove = '.circle' + elemID;
    let move = false;

    let marginStop = 30;
    let maxWidth = window.innerWidth - marginStop;
    let maxHeight = window.innerHeight - marginStop;

  $(contentMove).on('mousedown', function (e) {
    currentElemento = this.parentNode;       
    currentLeft = parseNumber(currentElemento.style.left);
    currentTop = parseNumber(currentElemento.style.top);

    startX = e.clientX;
    startY = e.clientY;
    if (typeof (callMoveOnElemento) == 'function')
      callMoveOnElemento(currentElemento);
    move = true;
  });

  $(document).on('mouseup', function () {
    if (currentElemento == null) return;
    if (typeof (callMoveStopElemento) == 'function')
      callMoveStopElemento(currentElemento);
    currentElemento = null;
    move = false;
  })

  $(document).on('mousemove', function (e) {
    if (move == true) {
      let newX = currentLeft + e.clientX - startX;
      let newY = currentTop + e.clientY - startY;

      if (marginStop > e.clientX) return;
      if (marginStop > e.clientY) return;
      if (maxWidth < e.clientX) return;
      if (maxHeight < e.clientY) return;

      $(currentElemento).css({
        'left': newX,
        'top': newY
      });

      coords = [{ "id": elemID, "latitude": newY, "longitude": newX }];
      self.trabalharRespostaFuncao(coords);
    }
  });

  return function (func1, func2) {
    callMoveOnElemento = func1;
    callMoveStopElemento = func2;
  }
})();
}

Function to prepare to fill the coordinate array

private trabalharRespostaFuncao(coords) {
  for (var coord of coords) {
    this.popularListaCoordenadas(coord);
  }
}

Function to feed coordinate array

private popularListaCoordenadas(coord) {
    this.coordenadas.push({
    id: coord.id, latitude: coord.latitude, longitude: coord.longitude
    });

}

I am open to suggestions, I thank you already.

  • The last coordinate is always the one with the id greater ?

  • No, each element has a different id. I need to get only the last x, y coordinate of each of these id.

  • Why not modify the method popularListaCoordenadas to use another dictionary only with the last coordinates of each id ?

  • That may be, but how do I do it? I still haven’t been able to extract the last coordinates from each id in isolation.

5 answers

1

in JS, the last element of any array can be obtained like this:

ultimoElemento = qualquerArray[qualquerArray.length-1];
  • Well, I’ve tried that, but it only takes the last position of the general array. I would like it to take the last position, where for example, ID 4 was found in the array.

  • Okay, I got it. Let’s get a better look at your code

1

A simple solution is to create the last coordinates as you add new ones with a dictionary, using the id as key for not having repeated ids.

All you need to do is change your method popularListaCoordenadas:

private popularListaCoordenadas(coord) {
    this.coordenadas.push({
        id: coord.id, latitude: coord.latitude, longitude: coord.longitude
    });

    if (!this.ultimasCoords){ //se não existe o dicionario cria
        this.ultimasCoords = {};
    }

    this.ultimasCoords[coord.id] = { //guarda a coordenada pelo id
        id: coord.id, latitude: coord.latitude, longitude: coord.longitude
    };
}

Now to use the last coordinates of each id needs only one for:

for (let idCoord of Object.keys(this.ultimasCoords)){
    let coordenada = this.ultimasCoords[idCoord];
    //fazer algo com a coordenada
}

Working example:

let coords = [
    {id: 6,latitude: 175,longitude: 601}, 
    {id: 6,latitude: 177,longitude: 604}, 
    {id: 6,latitude: 177,longitude: 604}, 
    {id: 5,latitude: 0,longitude: 1}, 
    {id: 5,latitude: 4,longitude: 4}, 
    {id: 5,latitude: 8,longitude: 9}, 
    {id: 5,latitude: 26,longitude: 37}, 
    {id: 5,latitude: 49,longitude: 95}, 
    {id: 5,latitude: 195,longitude: 448}, 
    {id: 5,latitude: 215,longitude: 499}, 
    {id: 5,latitude: 215,longitude: 500}, 
    {id: 3,latitude: 1,longitude: 2}
];

let obj = {
  coordenadas : [],
  popularListaCoordenadas : function(coord) {
    this.coordenadas.push({
      id: coord.id,
      latitude: coord.latitude,
      longitude: coord.longitude
    });

    if (!this.ultimasCoords) { 
      this.ultimasCoords = {};
    }

    this.ultimasCoords[coord.id] = {
      id: coord.id, latitude: coord.latitude, longitude: coord.longitude
    };
  }
};

for (let i = 0;i < coords.length; ++i){ 
  obj.popularListaCoordenadas(coords[i]);
}

for (let idCoord of Object.keys(obj.ultimasCoords)) {
  let coordenada = obj.ultimasCoords[idCoord];
  console.log(coordenada);
}

0

You need to scroll through your coordinate array and identify the object-coordinate index with the desired ID:

var coordenadas = [
    {id: 1, quantity: 2},
    {id: 2, quantity: 0},
    {id: 3, quantity: 5}
];

function findID(element, index, array) { 
    //forneça o id procurado aqui, ou vindo de outra variável
    var idSearch = 2;
    return element.id == idSearch ;
}

console.log(coordenadas.find(findID)); 
// {id: 2, quantity: 0}
  • I’ll run a test, and I’ll get back to you.

  • Don’t forget to adapt to your code!

  • But my coordinate array, before applying the function, looks like this: 37: {id: 6, latitude: 175, longitude: 601} 38: {id: 6, latitude: 177, longitude: 604} 39: {id: 6, latitude: 177, longitude: 604} 40: {id: 5, latitude: 0, longitude: 1} 41: {id: 5, latitude: 4, longitude: 4} 42: {id: 5, latitude: 8, longitude: 9} 43: {id: 5, latitude: 26, longitude: 37} 44: {id: 5, latitude: 49, longitude: 95} 45: {id: 5, latitude: 195, longitude: 448} 46: {id: 5, latitude: 215, longitude: 499} 47: {id: 5, latitude: 215, longitude: 500} 48: {id: 3, latitude: 1, longitude: 2}

  • The point is that amid these repeated ID elements, I want to get only the last registered of each ID.

  • I understand. For this case the answer is different from the one given to your initial question. I will reformulate and post a second answer

  • I posted a second answer that filters the results and generates a new vector with these elements that you seek.

Show 1 more comment

0

You need to scroll through your coordinate array and identify the indexes of the coordinate objects with the desired Ids:

    var coordenadas = [
        {id: 1, quantity: 2},
        {id: 2, quantity: 0},
        {id: 3, quantity: 5},
        {id: 4, quantity: 5},
        {id: 5, quantity: 5},
    ];

   //IDs que vc procura
    var targetIDs = [2, 5];

    function findID(element, index, array) { 
        //filtra elementos desejados
        return targetID.find(selement.id);
    }

    //vetor resultado
    var resultElements = coordenadas.filter(findID);

    console.log(resultElements); 
    // [{id: 2, quantity: 0 }, {id: 5, quantity: 5}]

0


You can scroll through each element keeping the last coordinate according to the id, overwriting the last occurrence. This ensures that at the end you will only have the last occurrence of each coordinate of id duplicate.

const coordenadas = [
    { id: 6, latitude: 175, longitude: 601 },
    { id: 6, latitude: 177, longitude: 604 },
    { id: 6, latitude: 177, longitude: 604 },
    { id: 5, latitude: 0, longitude: 1 },
    { id: 5, latitude: 4, longitude: 4 },
    { id: 5, latitude: 8, longitude: 9 },
    { id: 5, latitude: 26, longitude: 37 },
    { id: 5, latitude: 49, longitude: 95 },
    { id: 5, latitude: 195, longitude: 448 },
    { id: 5, latitude: 215, longitude: 499 },
    { id: 5, latitude: 215, longitude: 500 },
    { id: 3, latitude: 1, longitude: 2 }
];

let resultado = {};
coordenadas.forEach((item) => resultado[item.id] = item);

console.log(resultado);

  • This simple solution worked for me. I thank everyone who tried to help me.

  • @Maiconcosta consider marking the answer as accepted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.