-3

I'm getting names back from this array. There are duplicated names (example: "Kenny") that are returned two times and I only want to push it into the new array once. I'm kinda lost in the process. Here's what I have done so far.

var newArr = [];



$.ajax({
    url: 'https://spreadsheets.google.com/feeds/list//od6/public/values?alt=json',
    success: function(data){
        var entryPoint = data.feed.entry;
        // data.feed.entry entry to arrays 
        for (i = 0; i < entryPoint.length; i++){
            var fName = entryPoint[i].gsx$firstname.$t;
            var lName = entryPoint[i].gsx$lastname.$t;
            var email = entryPoint[i].gsx$email.$t;
            var total = entryPoint[i].gsx$totalordered.$t;


            newArr.push(fName)

        }

    }


})
kenny
  • 438
  • 4
  • 14
  • Possible duplicate of [Array.push() if does not exist?](https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist) – arpl Dec 17 '17 at 01:08

3 Answers3

3

newArr.indexOf(value) will return -1 if not found

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
1

Use this:

var newArr = [];
var found;

$.ajax({
url: 'https://spreadsheets.google.com/feeds/list//od6/public/values?alt=json',
success: function(data)
{
    var entryPoint = data.feed.entry;
    // data.feed.entry entry to arrays

    for (i = 0; i < entryPoint.length; i++)
    {
        var fName = entryPoint[i].gsx$firstname.$t;
        var lName = entryPoint[i].gsx$lastname.$t;
        var email = entryPoint[i].gsx$email.$t;
        var total = entryPoint[i].gsx$totalordered.$t;

        found = false;

        // Check the array for the name
        for(var i=0; i < newArr.length; i++)
        {
            if(newArr[i] == fName)
            {
                found = true;
                break;
            }
        }

        // If name not found, add it
        if(!found) newArr.push(fName)
    }
}
});
Ivan86
  • 5,695
  • 2
  • 14
  • 30
0

If newArr needs to contain unique values, it should be a Set, not an Array. You can put the names into a Set by passing the constructor an array:

var newSet = new Set(entryPoint.map(entry => entry.gsx$firstname.$t));

Any name that's already been added to the set will be skipped. You can then get an Iterator to work with the stored names using newSet.values(), or, if you're more comfortable, use it to create an array based on the set:

var newArr = [...newSet.values()];
// or var newArr = Array.from(newSet.values()); if you can't use destructuring

All that being said, Set isn't available in Internet Explorer. But you can polyfill it with, among other things, polyfill.io.

AuxTaco
  • 4,883
  • 1
  • 12
  • 27