1

Out of curiosity, is there any way to display inverted array index. Let's say we got this as our array:

var color = ["red", "green", "blue", "yellow"];
console.log(color[2]);

Of course the console will show "blue" right?

What if I want to display other than "blue"? That mean "red", "green", "yellow". Or should we use slice instead?

Thank you

1
  • 2
    Use filter ["red", "green", "blue", "yellow"].filter((c,i) => i !== 2) Commented Sep 2, 2021 at 10:47

4 Answers 4

1

You can use .filter() to filter out elements. So, in this case filter out all the elements of the array which is not blue.

var color = ["red", "green", "blue", "yellow"];
console.log(color.filter(col => col !== "blue"));
Sign up to request clarification or add additional context in comments.

Comments

1

1) You can use a filter here

var color = ["red", "green", "blue", "yellow"];
const result = color.filter((c) => c !== "blue");
console.log(result);

2) Although you can also use splice

var color = ["red", "green", "blue", "yellow"];
const newArray = [...color];
newArray.splice(2, 1);
console.log(newArray);

Comments

1

If I got it right what you want, so show everything EXCEPT the one which's index you pass, then:

myFun = (myArray, n) => {
  return myArray.slice(0, n).concat(myArray.slice(n+1))
}
color = ["red", "green", "blue", "yellow"]
myFun(color, 2)

// ["red", "green", "yellow"]

Comments

0

From what I can infer from your question is - you wish to pass in an index and get everything from the array except for the element at the index you passed, and whether there's a direct array helper that we can use. I think there's none so you might as well want to create your own :D

Array.prototype.invertedArrayWithIndex = function(indexOfChoice){
        var _array = this;
        return _array.filter(function(ele, index){
         return _array.indexOf(ele) !=  indexOfChoice
    })
}

var color = ["red", "green", "blue", "yellow"];

color.invertedArrayWithIndex(2); // Array(3) [ "red", "green", "yellow" ]

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.