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
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"));
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);
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"]