Array.Prototype.Splice in Ruby

Array.prototype.splice in Ruby

Use Array#[]=.

a = [1, 2, 3, 4, 5, 6]
a[2..4] = [:foo, :bar, :baz, :wibble]
a # => [1, 2, :foo, :bar, :baz, :wibble, 6]

# It also supports start/length instead of a range:
a[0, 3] = [:a, :b]
a # => [:a, :b, :bar, :baz, :wibble, 6]

As for returning the removed elements, []= doesn't do that... You could write your own helper method to do it:

class Array
def splice(start, len, *replace)
ret = self[start, len]
self[start, len] = replace
ret
end
end

Array.splice() behaves one way on array literal and another way on array saved as const

splice will do two things:

  • It will remove (or add) the items from the array, given the arguments (first argument is index, second argument is number of items to remove)
  • It will return the removed items as an array

It does not return the changed (or original) array. So

const foo = [1,2,3,4].splice(2, 1);
console.log("foo", foo);

is behaving as expected; it's removing the item at index 2 (which is 3) and returning it as an array, so foo evaluates to [3] (an array containing the single removed item).

With

const bar = [1,2,3,4]
bar.splice(2, 1);
console.log("bar", bar);

the item at index 2 is being removed from the bar array, but then you proceed to log the altered bar array, with the 3 item removed, so the result is [1, 2, 4].

Might be clearer if you assigned the result of the splice call to something and then logged that other variable:

const arr = [1,2,3,4]const removedItems = arr.splice(2, 1);console.log("arr", arr);console.log("removedItems", removedItems);

Equivalent of Ruby's each_cons in JavaScript

Here is a function that will do it (ES6+):

// functional approachconst eachCons = (array, num) => {    return Array.from({ length: array.length - num + 1 },                      (_, i) => array.slice(i, i + num))}
// prototype overriding approachArray.prototype.eachCons = function(num) { return Array.from({ length: this.length - num + 1 }, (_, i) => this.slice(i, i + num))}

const array = [0,1,2,3,4,5]const log = data => console.log(JSON.stringify(data))
log(eachCons(array, 2))log(eachCons(array, 3))
log(array.eachCons(2))log(array.eachCons(3))

Remove all items after an index

Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:

var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";

Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and "returns" a number instead of a new array.

To address .splice usage, you can feed it a negative index, along with a huge number to chop off the end of an array:

var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";

How to replace elements in array with elements of another array

You can use the splice method to replace part of an array with items from another array, but you have to call it in a special way as it expects the items as parameters, not the array.

The splice method expects parameters like (0, anotherArr.Length, 1, 2, 3), so you need to create an array with the parameters and use the apply method to call the splice method with the parameters:

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));

Example:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var anotherArr = [ 1, 2, 3 ];

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));

console.log(arr);

Output:

[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Demo: http://jsfiddle.net/Guffa/bB7Ey/

Angular how to splice from Array with key?

You could use the the findIndex prototype method on the array to find key for the element you're looking for, e.g.

let index = this.checkedList.findIndex((element) => element["customer_id"] == option.id);

and then splice the array as you'd normally do.

this.checkedList.splice(index, 1);

How to replace item in array?

var index = items.indexOf(3452);

if (index !== -1) {
items[index] = 1010;
}

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

var items = [523, 3452, 334, 31, 5346];

You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:

var index = items.indexOf(3452);

if (~index) {
items[index] = 1010;
}

Sometimes I even like to write a contains function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:

var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
// do something else...
}

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

if (haystack.includes(needle)) {
// do your thing
}

How can I remove a specific item from an array?

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2, 9]
console.log(array);


Related Topics



Leave a reply



Submit