/    Sign up×
Bounties /Pin to ProfileBookmark

How do you remove a specific value from an array in JavaScript?

+ 1,000
Copy linkTweet thisAlerts:
Jul 02.2022
to post a answer
JavaScript

1 Replies

Copy linkTweet thisAlerts:
@toddDec 02.2022 — To remove a specific value from an array in JavaScript, you can use the Array.prototype.filter() method. This method creates a new array with all elements that pass the test implemented by the provided function. In this case, the function should check whether the element is equal to the value you want to remove, and return false if it is. Here is an example:


const array = [1, 2, 3, 4, 5];

// Create a new array with all elements that are not equal to 3.
const newArray = array.filter(element => element !== 3);

console.log(newArray); // Output: [1, 2, 4, 5]


This code uses the filter() method to create a new array with all elements that are not equal to 3. The resulting array is assigned to the newArray variable, which contains the elements 1, 2, 4, and 5. The original array is not modified by the filter() method.

Alternatively, you can use the Array.prototype.indexOf() and Array.prototype.splice() methods to remove the value from the array. The indexOf() method finds the index of the first occurrence of the value in the array, and the splice() method is used to remove that element at the specified index. Here is an example:


const array = [1, 2, 3, 4, 5];

// Find the index of the first occurrence of 3 in the array.
const index = array.indexOf(3);

// If the value is found in the array, remove it.
if (index !== -1) {
array.splice(index, 1);
}

console.log(array); // Output: [1, 2, 4, 5]


This code uses the indexOf() method to find the index of the first occurrence of 3 in the array. If the value is found, the splice() method is used to remove the element at that index. The resulting array contains the elements 1, 2, 4, and 5, and the original array is modified by the splice() method.

Both of these approaches are effective ways to remove a specific value from an array in JavaScript. Which method you choose will depend on your specific needs and preferences.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...