2016-05-18 3 views
-1

я могу использовать Array.splice, чтобы удалить какой-либо элемент из массиваСоздайте функцию, которая принимает массив и возвращает новый массив с числами, кратными X удалены

Я специально глядя @ кратные 3 и 5 в массиве

кратные X должны быть удалены

номер 3 и номер 5 кратные Что такое метод я должен написать для этого. Мне нужно использовать Vanilla Javascipt

var myArray = [1,2,3,5,9,15,16,21,23,25];

  function removeMultiples(ary, num) { 



      } 

      //removeMultiples(myArray, 3) => [1,2,5,16,23,25] 
      //removeMultiples(myArray, 5) => [1,2,3,9,16,21,23] 
      </script> 
+1

Вам нужно ** перебрать ** по массиву. Вы можете сделать это, используя цикл '' for' (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for). С какими особенностями у вас возникают проблемы? Мы будем рады помочь вам исправить ваш код, но мы не пишем код для вас. –

+0

Возможный дубликат [Удалить конкретный элемент из массива в JavaScript?] (Http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript) – AlwaysNull

+0

Вы можете также сделайте это с помощью [.filter] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) –

ответ

1

Это звучит как домашнее задание. Вот домашний ответ, который не зависит от встроенного метода Array.prototype.filter. Это простое рекурсивное определение использует постоянное время и пространство.

const removeMultiples = (n, xs)=> { 
    let loop = (ys, xs)=> { 
    if (xs.length === 0) 
     return ys; 
    else if (xs[0] % n === 0) 
     return loop(ys, xs.slice(1)); 
    else 
     return loop(ys.concat([xs[0]]), xs.slice(1)); 
    }; 
    return loop([], xs); 
}; 

removeMultiples(3, [0,1,2,3,4,5,6,7,8,9]); 
//=> [1,2,4,5,7,8] 

Это использует Array.prototype.filter и, вероятно, не научит вас ничего.

myArray.filter(x=> x % 3 !== 0); 
myArray.filter(x=> x % 5 !== 0); 

Это использует комбинацию простых функций для достижения своей цели. Преимущество этого подхода состоит в том, что каждая функция выполняет одну, простую вещь, и каждая функция очень многократно используется.

// (b->c) -> (a->b) -> (a->c) 
const comp = f=> g=> x=> f (g (x)); 

// Boolean -> Boolean 
const not = x=> !x; 

// Number -> Number -> Boolean 
const isDivisibleBy = x=> y=> y % x === 0; 

// Array -> Boolean 
const isEmpty = xs=> xs.length === 0; 

// [Value] -> Value 
const first = xs=> xs[0]; 

// [Value] -> [Value] 
const rest = xs=> xs.slice(1); 

// [Value] -> [Value] -> [Value] 
const concat = xs=> ys=> ys.concat(xs); 

// Value -> [Value] -> [Value] 
const append = x=> concat([x]); 

// (a->b->a) -> a -> [b] -> a 
const reduce = f=> y=> xs=> 
    isEmpty(xs) ? y : reduce (f) (f (y) (first (xs))) (rest (xs)); 

// (Value->Boolean) -> [Value] -> [Value] 
const filter = f=> 
    reduce (ys=> x=> f (x) ? append (x) (ys) : ys) ([]); 

// Number -> [Number] -> [Number] 
const removeMultiples = x=> 
    filter (comp (not) (isDivisibleBy(x))); 

Хорошо, теперь давайте посмотрим, что все функции работают вместе в гармонии!

removeMultiples (3) ([1,2,3,5,9,15,16,21,23,25]); 
//=> [ 1, 2, 5, 16, 23, 25 ] 

removeMultiples (5) ([1,2,3,5,9,15,16,21,23,25]); 
//=> [ 1, 2, 3, 9, 16, 21, 23 ] 
2

Prob хорошо использовать для фильтра:

Working Example

function removeMultiples(arr, mul) { 
    return arr.filter(function(el) { 
    return el % mul !== 0; 
    }) 
} 

Или с цикл:

function remove(arr, mul) { 
    var result = []; 
    for (var i = 0; i < arr.length; i++) { 
    if (arr[i] % mul) { 
     result.push(arr[i]); 
    } 
    } 
    return result; 
} 
2

Описание

Учитывая запятыми строку, если много цифры или строку с одним многозначным числом, вы можете использовать это регулярное выражение для замены ведущей запятой, а числа, равномерно делящиеся на 3 или 5 с нулевым значением.

(?:,|^)((?:[0369]|[258][0369]*[147]|[147](?:[0369]|[147][0369]*[258])*[258]|[258][0369]*[258](?:[0369]|[147][0369]*[258])*[258]|[147](?:[0369]|[147][0369]*[258])*[147][0369]*[147]|[258][0369]*[258](?:[0369]|[147][0369]*[258])*[147][0369]*[147])*|[0-9]*[50])(?=,|\Z)

более подробное объяснение этого выражения можно найти здесь: смотри также link

Заменить: ничего

Regular expression visualization

Пример

Демо

https://regex101.com/r/iG9lP4/1

Пример строки

1,2,3,5,9,15,16,21,23,25 

После замены

1,2,16,23 

Объяснение
NODE      EXPLANATION 
---------------------------------------------------------------------- 
    (?:      group, but do not capture: 
---------------------------------------------------------------------- 
    ,      ',' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    ^      the beginning of a "line" 
---------------------------------------------------------------------- 
)      end of grouping 
---------------------------------------------------------------------- 
    (      group and capture to \1: 
---------------------------------------------------------------------- 
    (?:      group, but do not capture (0 or more 
          times (matching the most amount 
          possible)): 
---------------------------------------------------------------------- 
     [0369]     any character of: '0', '3', '6', '9' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     (?:      group, but do not capture (0 or more 
           times (matching the most amount 
           possible)): 
---------------------------------------------------------------------- 
     [0369]     any character of: '0', '3', '6', '9' 
---------------------------------------------------------------------- 
     |      OR 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
    )*      end of grouping 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
     (?:      group, but do not capture (0 or more 
           times (matching the most amount 
           possible)): 
---------------------------------------------------------------------- 
     [0369]     any character of: '0', '3', '6', '9' 
---------------------------------------------------------------------- 
     |      OR 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
    )*      end of grouping 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     (?:      group, but do not capture (0 or more 
           times (matching the most amount 
           possible)): 
---------------------------------------------------------------------- 
     [0369]     any character of: '0', '3', '6', '9' 
---------------------------------------------------------------------- 
     |      OR 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
    )*      end of grouping 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
     (?:      group, but do not capture (0 or more 
           times (matching the most amount 
           possible)): 
---------------------------------------------------------------------- 
     [0369]     any character of: '0', '3', '6', '9' 
---------------------------------------------------------------------- 
     |      OR 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [258]     any character of: '2', '5', '8' 
---------------------------------------------------------------------- 
    )*      end of grouping 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
     [0369]*     any character of: '0', '3', '6', '9' 
           (0 or more times (matching the most 
           amount possible)) 
---------------------------------------------------------------------- 
     [147]     any character of: '1', '4', '7' 
---------------------------------------------------------------------- 
    )*      end of grouping 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    [0-9]*     any character of: '0' to '9' (0 or more 
          times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    [50]      any character of: '5', '0' 
---------------------------------------------------------------------- 
)      end of \1 
---------------------------------------------------------------------- 
    (?=      look ahead to see if there is: 
---------------------------------------------------------------------- 
    ,      ',' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    \Z      before an optional \n, and the end of 
          the string 
---------------------------------------------------------------------- 
)      end of look-ahead 
---------------------------------------------------------------------- 
+0

Ну, это, безусловно, * другое решение ... Мне нравится видеть другие способы решения проблем, но я боюсь, что это довольно незаметно. Почти невозможно проверить, что это работает правильно для всех натуральных чисел. Я полагаю, что решение для 5 было бы немного проще, '/ \ d * [05] /'. – naomik

+0

О, я полностью согласен с тем, что это нелегко поддерживать, но ОП задал регулярное выражение, которое соответствовало бы числам, равномерно делимым на три, и, по крайней мере, в живой демоверсии он работает так, как ожидалось, и это теория работы довольно тщательно проверен. –

+1

Я полностью пропустил ту часть, где он/она попросил регулярного выражения – naomik

Смежные вопросы