Darren Harley
Darren Harley

Reputation: 97

How does one remove number values and empty values from an array?

As part of my nightwatchjs testing, I have a dynamic array (in an object) that requires some tweaking.

My current array looks like this;

{ GenericColour:    [ 'Black',
     5059,
     'White',
     3610,
     'Grey',
     3281,
     'Blue',
     2131,
     'Silver',
     1408,
     'Red',
     1190,
     '',
     491,
     'Yellow',
     59,
     'Green',
     50,
     'Orange',
     31 ] }

but with it being dynamic, it might look slightly different the next time I run the test (a different colour might be added, or a current colour no longer listed, etc.).

What I would like to try and do is remove all the numbers, extra commas, etc. so I'm just left with an array reading (as per the example above);

['Black','White','Grey','Blue','Silver','Red','Yellow','Green','Orange']

Is there a way of doing this, either using JavaScript commands or regex?

Upvotes: 2

Views: 137

Answers (7)

Peter Seliger
Peter Seliger

Reputation: 13431

There are cases, where one can not reassign a filtered result to the original source reference. Like with ...

const arr = [1, 2, 3]; arr = arr.filter(/* ... */);

... which will fail. One also might need to deal with properties which are not allowed to be written but of cause still can be mutated.

Then one needs a mutating remove approach based on a callback, exactly of the kind that filter asks for, where this callback function is the condition of whether to remove an array item or not.

function removeEveryMatchingItemByCondition(arr, condition, target) {
  target = (target ?? null);

  let idx = arr.length;
  const copy = Array.from(arr);

  // Processing the array from RIGHT to LEFT keeps the `idx` always in sync
  // with both related array items, the one of the mutated and also the one
  // of the unmutated version of the processed array reference.
  // Thus the `condition` always gets passed the unmutated shallow copy.

  while (idx) {
    if (arr.hasOwnProperty(--idx)) { // take a *sparse array* into account.

      // - keep processing the unmutated shallow copy by the `condition` method.
      // - arguments list ...[elm, idx, arr]... invoked within `target` context.
      if (condition.call(target, copy[idx], idx, copy)) {

        arr.splice(idx, 1); // mutate processed array.
      }
    }
  }
  return arr; // return the mutated array reference.
}


const sampleObject = {
  GenericColour: [
    'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver',
    1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31
  ],
};

removeEveryMatchingItemByCondition(
  sampleObject.GenericColour,
  // exactly what the OP was asking for in first place.
  (item => typeof item === 'number' || String(item).trim() === '')
);
console.log(sampleObject);

removeEveryMatchingItemByCondition(
  sampleObject.GenericColour,
  (item => typeof item === 'string')
);
console.log(sampleObject);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

One way is to filter based on checking length propterty.

For numbers and '', the length value is 0 (false).

const data = [ '', 'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver', 1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31 ];

const res = data.filter(str => str.length);

console.log(res);

Upvotes: 0

Alex.B
Alex.B

Reputation: 41

Simplest way would be passing isNaN to the filter method.

const a = [ 'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver', 1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31 ];
const b = a.filter(isNaN);
console.log(b);

Upvotes: 0

Ayoub Touba
Ayoub Touba

Reputation: 2997

You do that with the filter function:

obj = obj.GenericColour.filter(value => typeof value === 'string' )

Upvotes: 1

Yavor Dimitrov
Yavor Dimitrov

Reputation: 3

You can use array.prototype.filter to check for items in the array that are strings, removing all other items e.g. numbers. Check the link below for more info.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

it can be something like this:

array.filter((item) => typeof item === "string"); - this will return a new array with only the strings in the current array:

['Black','White','Grey','Blue','Silver','Red','Yellow','Green','Orange']

Upvotes: 0

Fahad Tahir
Fahad Tahir

Reputation: 112

    int numberArry = []
    arry.forEach(value => if(isNaN(value)) numberArry.push(value));

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89374

You can use Array#filter, using the typeof operator to check if the element is a string.

const arr = [ 'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver', 1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31 ];
const res = arr.filter(x => typeof x === 'string' && x);
console.log(res);

Upvotes: 4

Related Questions