dcsimg
www.webdeveloper.com
Results 1 to 7 of 7

Thread: Delete 4 count occurrences in an array - help

  1. #1
    Join Date
    May 2017
    Posts
    3

    Delete 4 count occurrences in an array - help

    I have an array and I want to delete all occurrences of count of 4 in an array. How do I get back the remaining array?

    array = [1,1,2,2,2,3,3,6,6,6,6,7,7,7,9]

    I want the result array back:
    [1,1,2,2,2,3,3,7,7,7,9]

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,429
    Not clear...

    All counts of 4 as in Number 4 or all entries at array position 4?


    array = [1,1,2,2,2,3,3,6,6,6,6,7,7,7,9] has 15 elements

    if you remove all counts that are array position 4 will eventually return an array of

    array = [1,1,2,2]

    You say you want :
    [1,1,2,2,2,3,3,7,7,7,9]

    which is not array position 4 but 7,8,9,10 of the array that has been removed in your example.

    If you want to remove an element from an array, you use splice() to remove the element.

    So it is best to clarify what you are tying to achieve, remove array element 4 or remove elements that have 4 entries the same ...
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Dec 2012
    Posts
    1,555
    If I understand you correctly, this should do the job:
    Code:
            var arr = [1, 1, 2, 2, 2, 3, 3, 6, 6, 6, 6, 7, 7, 7, 9];
            var help = [];
            arr.forEach(function (val, idx) {
                if (!help[val]) help[val] = 0;
                help[val]++;
            });
            var newarr = arr.filter(function (val, idx) {
                if (help[val] == 4) return false;
                return true;
            });
            console.log(help, newarr);

  4. #4
    Join Date
    May 2017
    Posts
    3
    I would like to remove elements with same entries 4 times.

  5. #5
    Join Date
    Dec 2012
    Posts
    1,555
    My code does exactly this.

  6. #6
    Join Date
    May 2017
    Posts
    3
    yes! Thank you. Exactly what I wanted. Again - thank you very much.

  7. #7
    Join Date
    Sep 2008
    Location
    Jackson MS
    Posts
    563
    -deleted by author`

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center