Shiro Gin
Shiro Gin

Reputation: 19

Javascript error: .remove is not a function

I have a field that displayed list of "Template name".

The remove button supposedly will delete the Template name, but somehow failed to delete the selected Template from display.

  let EditChannelForm = props => {
  const {channelKeys, channelType} = props;
  let fields;
  
  if (channelKeys) {
    fields = channelKeys.map((ck, index) => {
    
      if(ck.key === "templateName") {
   
        return (
          <div  key={ck.key+ index}>
        <li key={ck.key + index} style={styl}>
        <Field
          component={renderField}
          validate={[required]}
          label={changeCase.titleCase(space(ck.key))}
          name= {ck.key + index}
      />

 <Button type="danger" icon="delete" onClick={() => channelKeys.remove(ck.key + index)} >Remove</Button>
              
              </li>
              </div>

I got the error

channelKeys.remove is not a function

Is there anything I need to change in onClick={() => channelKeys.remove(ck.key + index)} ?

Upvotes: 0

Views: 1357

Answers (1)

Dhruvi Makvana
Dhruvi Makvana

Reputation: 905

There is no function such as Array.prototype.remove. Please see the docs.

If you want to remove a specific item from the array use Array.prototype.filter.

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)

same can be used for the object-based array.

let cities = [
    {name: 'Los Angeles', population: 3792621},
    {name: 'New York', population: 8175133},
    {name: 'Chicago', population: 2695598},
    {name: 'Houston', population: 2099451},
    {name: 'Philadelphia', population: 1526006}
];

let bigCities = [];
for (let i = 0; i < cities.length; i++) {
    if (cities[i].population > 3000000) {
        bigCities.push(cities[i]);
    }
}
console.log(bigCities);

Edit:

let cities = [
    {name: 'Los Angeles', population: 3792621},
    {name: 'New York', population: 8175133},
    {name: 'Chicago', population: 2695598},
    {name: 'Houston', population: 2099451},
    {name: 'Philadelphia', population: 1526006}
];

let bigCities = [];

function remove(cityName){
  for (let i = 0; i < cities.length; i++) {
      if (cities[i].name !== cityName) {
          bigCities.push(cities[i]);
      }
  }
  return bigCities;
}
console.log(bigCities);
<Button type="danger" icon="delete" onClick={() => remove(ck.name)} >Remove</Button>

Upvotes: 1

Related Questions