0

I have 2 arrays:

ids = [a,b,c,d,e,f....];

savedRepods = [e,f];

  function getPoints(){
      for (var i = 0; i < savedRepods.length; i++) {
        if(ids.includes(savedRepods[i]) ) {
          console.log(savedRepods[i]);
        }
      }
  }

I know the value is in the array but this won't show me the value console.log(savedRepods[i]);

Full code:

  /** get saved values from the server */
  var savedRepods = <?php echo json_encode($userPostsInternal); ?> ;
  savedRepods = savedRepods.split(",");

  /** create single arrays for the values */

  var date = [],
      coords = [],
      ids = [],
      metal = [],
      plastic = [],
      paper = [],
      glass = [],
      indirizzo = [];

  /** convert to a variable ALL the other values form the server */

  var array = <?php echo $contents; ?> ;

  /** push single values into correspondent arrays */

  array.map(function(item) {
      coords.push(item.Lat + "," + item.Lng);
      ids.push(item.ID);
      date.push(item.Date);
      plastic.push(item.Plastic);
      paper.push(item.Paper);
      glass.push(item.Glass);
      metal.push(item.Metal);
  });


  /**
   * Now process the response from locationData
   */
  var locations = getPoints();

  /**
   * findLatLang
   */
  function findLatLang(location, geocoder, value) {
      /**
       * Return new Promise what resolves when 
       * the geocoder is successfull
       * and push in the array of promises
       */
      return new Promise(function(resolve, reject) {
          /** Do geocoder */
          geocoder.geocode({
              'location': location
          }, function(results, status) {
              /**
               * If geocoder is Ok
               */
              if (status === 'OK') {
                  /**
                   * When the geocoder is successfull located
                   * resolve the promise and send the response of formate address
                   */
                  resolve([results[0].formatted_address, value]);
              } else {
                  /**
                   * Reject the promise
                   */
                  reject(new Error('Couldnt\'t find the location ' + location));
              }
          })
      })
  }

  /**
   * processData 
   * return an array of promises
   */
  function getPoints(){
      /**
       * Declare a variable of promises that have a geocoder
       */
      let locationData = [];
      for (var i = 0; i < savedRepods.length; i++) {

        if(ids.includes(savedRepods[i]) ) {

          console.log(savedRepods[i]);

          var geocoder = new google.maps.Geocoder;
          var latlngStr = coords[a].split(',', 2);
          var latlng = {
              lat: parseFloat(latlngStr[0]),
              lng: parseFloat(latlngStr[1])
          };

          /**
           * Push geocoder in array of locationdata
           * Send the geocoder object on function and send the map
           */
          locationData.push(findLatLang(latlng, geocoder, a))
        }
      }

      /** return array of promises */
      return locationData;
  }

  Promise.all(locations)
    .then(function(returnVals){
    indirizzo = returnVals;
    doAddress(indirizzo)
  });

  var usedId = [],
      usedMetal = [],
      usedGlass = [],
      usedPaper = [],
      usedLocation = [],
      usedPlastic = [];


      const data = [];

  function doAddress(indirizzo) {
    indirizzo.forEach(function(item){
      var a = item[1];
      var location = item[0];

      let newObj = {};
      newObj.idValue = ids[a];
      newObj.addressValue = location;
      newObj.metalValue = metal[a];
      newObj.glassValue = glass[a];
      newObj.plasticValue = plastic[a];
      newObj.paperValue = paper[a];
      data.push(newObj);

      $("#eachValue ul").append("<li class='list-group-item'>repod id= " + ids[a] + "<br> Indirizzo = " + location + "<br> Metallo = " + metal[a] + ", <br> Plastica = " + plastic[a] + ", <br> Vetro = " + glass[a] + ", <br> Carta = " + paper[a] + "</li>");
    })

    const resultMetal = data.sort((a, b) => b.metalValue - a.metalValue)[0];
    const resultGlass = data.sort((a, b) => b.glassValue - a.glassValue)[0];
    const resultPaper = data.sort((a, b) => b.paperValue - a.paperValue)[0];
    const resultPlastic = data.sort((a, b) => b.plasticValue - a.plasticValue)[0];

    $("#metal p").html("Il repod con id "+resultMetal.idValue+"<br>situato in <br>" + resultMetal.addressValue + "<br> ha consumato più metallo con un valore di " + resultMetal.metalValue);
    $("#vetro p").html("Il repod con id "+resultGlass.idValue+"<br>situato in <br>" + resultGlass.addressValue + "<br> ha consumato più vetro con un valore di " + resultGlass.glassValue);
    $("#plastica p").html("Il repod con id "+resultPlastic.idValue+"<br>situato in <br>" + resultPlastic.addressValue + "<br> ha consumato più plastica con un valore di " + resultPlastic.plasticValue);
    $("#carta p").html("Il repod con id "+resultPaper.idValue+"<br>situato in <br>" + resultPaper.addressValue + "<br> ha consumato più carta con un valore di " + resultPaper.paperValue);


  }
12
  • The code that checks for overlapping elements works fine. Commented Mar 3, 2020 at 2:25
  • @danh that's strange, I get Uncaught (in promise) TypeError: Cannot read property 'idValue' of undefined but Commented Mar 3, 2020 at 2:27
  • 1
    While your array includes both e and f, it does not include [e,f]. Commented Mar 3, 2020 at 2:29
  • @PM77-1 yeah it was just an example Commented Mar 3, 2020 at 2:30
  • @PM77-1 the code checks for elements of array savePods in ids. Commented Mar 3, 2020 at 2:31

1 Answer 1

1

Probably because of array entries are object types. Array.prototype.contains are not working for object types. Because in js:

var a = {
  prop: 'value'
}

var b = {
  prop: 'value'
}

if (a != b) {
  console.log('a is not equal to b');
}

In javascript = (equals) operator checks for references are same or not for object types. Reference is address of the object in memory. In my first example a and b has its own different reference so for javascript a is not equals to b.

Instead of contains you can use some method which requires a callback to manually check matches. Here's an example using some method to find an element is exists or not.

var array = [
  { name: 'Anna', age: 19 },
  { name: 'Sara', age: 17 },
  { name: 'John', age: 21 },
  { name: 'Doe', age: 34 }
]

var john = { name: 'John', age: 21 };

if (array.some((other) => {
  return other.name == john.name && other.age == john.age
})) {
  console.log('John is exists in the array');
}

If you don't want to check each property for objects you may check for JSON.stringfy(other) == JSON.stringfy(john).

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

12 Comments

thanks but i think the comparison is fine, I must have something in promise. If I have 5 ids it's ok but if I add a 6th then it won't work. I had removed singles ids just to check if any of them had some issues but not. So since I don't have any type of limiter like 5 or 6, then something gets wrong after 5 with promise. I'm just guessing, this is driving me mad.
maybe this for (var i = 0; i < savedRepods.length; i++) { for (var a = 0; a < ids.length; a++) { is giving +1 in promise and that's why is jumping the index and creating the issue?
@rob.m could you share console.log(ids) output?
console.log(ids) > (51) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51]
console.log(savedRepods) > ["33", "35", "26", "20", "18", "24"]
|

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.