Search code examples
javascriptarraysapiobjectif-statement

l want to check if value in array of object dublicated then show one of them on


  let all_map: [
    {
      "name": "sy map",
      "civilization": "sham",
      "continent": "Asia",
      "country": "damascuse",
      "price": 0.0
    },
    {
      "name": "sy map subscribe",
      "civilization": "sham",
      "continent": "Asia",
      "country": "damascuse",
      "price": 0.0
    }
  ]

How can I create an if statment to check if the country property has the same value as ("country": "damascuse") in the object to show only one of them?


Solution

  • You haven't explained your desired result well, but if I'm understanding correctly, you want to filter out duplicate countries from this array. My thought is to use Array.reduce() to iterate through and create a new array:

    const reducedMap = all_map.reduce((accumulator, current) => {
      if (accumulator.findIndex(x => x.country === current.country) === -1) {
        accumulator.push(current);
      }
      return accumulator;
    }, []);
    

    You didn't specify if you need to keep a specific one if there are duplicates. If that's the case, and, for example, you always want to keep the country that has "subscribe" in the name, then, when a duplicate country is reached in the reducer's iteration, you could add a regex conditional and splice the new object into the array in place of the old one, like so:

    const reducedMap = all_map.reduce((accumulator, current) => {
      const countryIndex = accumulator.findIndex(x => x.country === current.country);
      if (countryIndex === -1) {
        accumulator.push(current);
      } else {
        if (!/subscribe/.test(accumulator[countryIndex].name)) {
          accumulator.splice(countryIndex, 1, current);
        }
      }
      return accumulator
    }, []);