1

Lets say that I am to remove the oldest element of an array, because I wanted to replace it with a new value. (first-in-first-out).

For example, I have this array of values

var arr = [1,2,3,4,5,6,7]

And I wanted to only get the first three, values, and then on the 4th, replace the element who came first

[1,2,3], [4,2,3], [4,5,3] and so on..

I came up with a solution

var arr = [1,1,2,3,4,5,6,7];
var newArr = [];
for(i=0; i<arr.length; i++){
    if(newArr.length == 3 && newArr.indexOf(arr[i]) < 0) {
       newArr[i%3] = arr[i];
    } else if(newArr.indexOf(arr[i]) < 0) {
       newArr.push(arr[i])
    }
    console.log(newArr)
}

Which will render:

1
1
1,2
1,2,3
1,4,3
1,4,5
6,4,5
6,7,5

Instead of

1
1,2
1,2,3
4,2,3
4,5,3
4,5,6
7,5,6

What am I missing out.

5
  • Perhaps a sense of reason for doing this and logic Commented Oct 13, 2013 at 8:37
  • 1
    Any reason why you're also testing for unique values? if(newArr.indexOf(arr[i]) < 0) Commented Oct 13, 2013 at 8:38
  • who the hell downvote the question without a comment! Commented Oct 13, 2013 at 9:09
  • @godfrzero, when you are assigning jobs, you won't do the same job for right? Commented Oct 13, 2013 at 9:10
  • @JoeySalacHipolito No idea what the context for the code is, just asked for clarification :D Commented Oct 13, 2013 at 13:29

1 Answer 1

2
var arr = [1, 1, 2, 3, 4, 5, 6, 7];
var newArr = [], currentIndex = 0;
for (i = 0; i < arr.length; i++) {
    if (newArr.length === 3 && newArr.indexOf(arr[i]) < 0) {
        newArr[currentIndex % 3] = arr[i];
        currentIndex += 1;
    } else if (newArr.indexOf(arr[i]) < 0) {
        newArr.push(arr[i]);
    }
    console.log(newArr)
}

Output

[ 1 ]
[ 1 ]
[ 1, 2 ]
[ 1, 2, 3 ]
[ 4, 2, 3 ]
[ 4, 5, 3 ]
[ 4, 5, 6 ]
[ 7, 5, 6 ]

You just need to track the current index where you need to place the number using a separate variable.

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

Comments

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.