React Dev
React Dev

Reputation: 420

javascript - removing an array element

I'll pseudocode this to begin:

array = copper, oil, silver, bronze, gold, iron

user inputs the letter 'l'

if (the input has the letter 'l', remove everything from the array except words with 'l') {

output = copper, bronze, iron

my code:

//arr = iron, oil, gold, silver, bronze

classDiv = document.getElementsByClassName("searchOutputName");

for(var i = 0; i < arr.length; i++){

   market = arr[i];

   var n = market.indexOf(userInput.value);

      if (n >= 0) {
      classDiv[i].appendChild(document.createTextNode(arr[i]));

}
else {
      //do nothing
}

I have 5 div boxs for my search function.

If the user inputs 'l' the first box is empty, then it says oil, gold, silver, then another empty box. I want to make it so they stack up... first box has oil, then gold, then silver then 2 empty boxs.

Upvotes: 1

Views: 79

Answers (4)

Praveen
Praveen

Reputation: 56539

Though I have not added html to your code, I have managed to do it with JS which can be reworked to fit your need.

var arr = ["copper", "oil", "silver", "bronze", "gold", "iron"];

for (var i = 0; i < arr.length; i++) {
    if (arr[i].indexOf('l') !== -1) {
        arr.splice(i, 1); // Remove the element from array
        i = i - 1;  // Equalize to manage the removed array length
    }
}
console.log(arr);  //returns ["copper", "bronze", "iron"] 

JSFiddle (Based on the pseudocode you have posted)

Upvotes: 1

pid
pid

Reputation: 11607

This is the code you should use. It works, contrary to the other answer which has a bug.

function filter(items, criteria)
{
  var i, result;

  result = [];
  for (i = 0; i < items.length; i++)
  {
    if (items[i].indexOf('l') !== -1)
    {
        result.push(items[i]);
    }
  }

  return result;
}

You can filter by the criteria this way:

// market  = [ 'copper', 'oil', 'silver', 'bronze', 'gold', 'iron' ];
// userInput = '1';

subset = filter(market, userInput);

Upvotes: 0

Raul Guiu
Raul Guiu

Reputation: 2404

You also could use filter for the javascript:

var arr = ["copper", "oil", "silver", "bronze", "gold", "iron"];
arr = arr.filter(function(item){ return item.indexOf('l')>=0;});
console.log(arr);

Upvotes: 3

Ryan Buckley
Ryan Buckley

Reputation: 106

Sounds like you just want to sort the array by the elements that match the user input. How about something like this?

var text = 'l', t = ['iron', 'oil', 'gold', 'silver', 'bronze']
t.sort(function(a, b) { return a.indexOf(text) < b.indexOf(text) })
// => ["oil", "gold", "silver", "iron", "bronze"]

Upvotes: 0

Related Questions