React: Add values from array in another array - javascript

I'm trying to do this kind of operation but I don't understand how to do.
I have two array:
array1 = [elem1, elem2, elem3]
and a second array:
array2 = [elemA, elemB, elemC]
What i would to obtain is:
arrayFinal = [elem1:elemA, elem2:elemB, elem3:elemC]
How can I do??
Thank you so much.
EDIT:
the arrayFinal is not key:value, but the elem1:elemA is only the first value, elem2:elemB is the second value, for example using a join.
EDIT2:
I make an example of valure of array:
array1 = [0, 20, 40, 60, 80]
array2 = [-97:61:-1008; -97:60:-1008; -97:73:-1006, -98:70:-1008]
arrayFinal = [0:-96:61:-1009, 20:-97:61:-1008, 40:-97:60:-1008, 60:-97:73:-1006, 80:-98:70:-1008]

I See that there is a lot of confusion going on in the answers/comments, some people think you want to combine the arrays into key/value pairs, while others think you want to concat the arrays, while others think you want to make it an array where array1 is the index and array2 is the value at that index.
This is all caused by your formatting of [Elem1:ElemA, Elem2:ElemB]. which isnt even valid JS as far as i am aware.
However you edited your question, and now it seems like you want to combine them like [[Elem1, ElemA], [Elem2, ElemB]] in which case you can do that really easily in this way:
const array1 = ["elem1", "elem2", "elem3"];
const array2 = [1, 2, 3];
const result = array1.map((key, i) => [key, array2[i]]);
this will yield the result: [ [ 'elem1', 1 ], [ 'elem2', 2 ], [ 'elem3', 3 ] ]

You can do it like this:
const array1 = [0, 20, 40, 60, 80];
const array2 = ["-97:61:-1008;", "-97:60:-1008;", "-97:73:-1006", "-98:70:-1008"];
const arrayFinal = array1.map((item,index) => `${item}:${array2[index]}`);

If you are sure both arrays have the same length you can loop through the first one with a map and do something like that:
const arrayFinal = array1.map((item, i) => ({[item]: array2[i]}));
You'll get:
arrayFinal = [{elem1: elemA}, {elem2: elemB}...]
const array1 = ['item1', 'item2', 'item3'];
const array2 = [1, 2, 3];
const arrayFinal = array1.map((item, i) => ({[item]: array2[i]}));
console.log(arrayFinal);

Your case is very close to the following utility functions:
https://lodash.com/docs/4.17.15#zip
https://ramdajs.com/docs/#zip
Also, it could be implemented as follows:
function zip<A, B>(listA: A[], listB: B[]): Array<[A, B]> {
return listA.map((a, i) => [a, listB[i]]);
}
https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABALxgBwDwEEA0iBCAfABQA2MAzlFgFyJYDaAunuVfnfswJR1YBO-AIYBPDA1wEmhRAG8AUIkT8AplBD8kbagDoAtkLTFiQvDG6IAvDIanE2rjCZNuAbnkBfefIgIKcUhUdUjgAc2JUIwYARhwAJhwAZhZEBgAWHABWHAA2FzcgA
If you want a dictionary:
function zipObject<A extends (string | number | symbol), B>(listA: A[], listB: B[]): { [key in A]: B } {
return Object.assign(
{},
...listA.map((a, i) => ({ [a]: listB[i] })),
);
}

Related

Convert 2D nested array into 1D array in JavaScript?

Given a 2D array as shown in the example, how to manage to combine the string digits into one.
ex: Array2 = [[1,2,3],[4,5,6],[7,8,9]];
required sol:
Array1 = [123, 245, 789];
You can deconstruct your task into two separate problems, that we will solve in turn.
We need to take an array of numbers (e.g. [1, 2 ,3]) and join them together into a string (e.g. '123').
There is, in fact, a dedicated function for this in JavaScript - the join() function:
[1, 2, 3].join(''); // '123'
We need to perform the previous function on each object in an array, returning an array of the transformed objects.
JavaScript again has you covered, this time with the map() function:
[a, b, c].map((element) => foo(element)); // [foo(a), foo(b), foo(c)]
All we have to do now is join these too together, so that the operation we perform on each element of the parent array, is to join all of the child elements together:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]].map((array) => array.join('')); // ['123', '456', '789']
function foo(arr){
let toReturn = [];
for(let i = 0;i < arr.length;i++){
toReturn.push(arr[i].join(""));
}
return(toReturn);
}
console.log(foo([[1,2,3],[4,5,6],[7,8,9]]));
You can use reduce to aggregate your data combined with .join('') to get all element items of each array item into a single value like below:
const data = [[1,2,3],[4,5,6],[7,8,9]];
const result = data.reduce((acc, curr) => {
acc.push(curr.join(''));
return acc;
}, []);
console.log(result);
Return all files as a 1D array from given path
const fetchAllFilesFromGivenFolder = (fullPath) => {
let files = [];
fs.readdirSync(fullPath).forEach(file => {
const absolutePath = path.join(fullPath, file);
if (fs.statSync(absolutePath).isDirectory()) {
const filesFromNestedFolder = fetchAllFilesFromGivenFolder(absolutePath);
filesFromNestedFolder.forEach(file => {
files.push(file);
})
}
else return files.push(absolutePath);
});
return files
}

Pass array to function with .slice and .push together

Is there a shorter way of doing this:
let arrSlicePush = arr.slice();
arrSlicePush.push(num);
let x = func(arrSlicePush);
Thanks in advance.
Simply do:
func([...arr, num]);
Worth noting that Array.push returns the length of the array anyway, so the first example is irrelevant.
You would call Array.prototype.concat instead of Array.prototype.push.
Also, since concat already merges two arrays and returns a new one, you so not even need to slice the original array.
const arr = [ 0, 1, 2, 3, 4 ];
const num = 5;
const func = (arr) => arr.map(e => String.fromCharCode(e + 65));
const x = func(arr.concat(num));
console.log(x);
Notes
[ ...arr, val ] is syntactic sugar for arr.concat(val)
This works:
func(animals.slice().concat(num));

Can I use map function with 2 arrays?

I was wondering if any function exist that can do something like that
I already tried zipWith and some variations of the map, but no good results.
Only working solution to this is 2x ForEach, but I was wondering if I can minimalize this to one function
_.map( (array1, array2), function(knownValue, indexOfArray1, indexOfArray2) );
What I need is to increase array1 and array 2 indexes simultaneously (like: a1: 1, a2: 1; a1: 2, a2: 2; ...).
This arrays have also other types of values
#EDIT
I messed a little.
What i really wanted is to make this wrongly writed code to work
_.map( (array1, array2), (valueOfArray1, valueOfArray2), someFunction(knownValue, valueOfArray1, valueOfArray2) );
So my intention is:
For array1 and array2 elements, execute the function "someFunction", and in the next increment, use the next element of each array.
Like :
_.map( (array1, array2), (array1[0], array2[0]), someFunction(knownValue, array1[0], array2[0]) );
and next
_.map( (array1, array2), (array1[1], array2[1]), someFunction(knownValue, array1[1], array2[1]) );
but I want it more elegant :P
PS (Sorry for this mess)
Here is an example with flatMap:
const arr1 = [1,3,5];
const arr2 = [2,4,6];
console.log(arr1.flatMap((x,i) =>[x, arr2[i]]))
Since you already seem to be using lodash (or something similar) the .zip should work. The only pitfall is that .zip produces "pairs" with one from each original array IN a new array.
So when you map over the result from the .zip, the first argument is an array. See the example below and note that I'm destructuring the first argument with
function([a1_item, a2_item], indexForBoth) { .. rest of function here }
const a1 = ['a', 'b', 'c'];
const a2 = ['One', 'Two', 'Three'];
const result = _.zip(a1, a2).map(function([a1_item, a2_item], indexForBoth) {
return a1_item + a2_item + indexForBoth;
});
console.log("a1", a1);
console.log("a2", a2);
console.log("a1 zipped with a2", _.zip(a1, a2) );
console.log("Result after mapping and concatinating", result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>
Since they both have the same number of items, you can loop through array1 using map. The second parameter of map callback is the index. You can use it to get the equivalent value from array2 using array2[index]
array1.map((value1, index) => someFunction(knownValue, value1, array2[index]))
This creates an array of values returned by someFunction for each index
Here's a snippet with some sample data. Here, someFunction concatenates each value with a _ seperator
const someFunction = (...values) => values.join('_')
const array1 = [1, 2, 3],
array2 = [10, 20, 30],
knownValue = "fixed";
const output = array1.map((value1, i) => someFunction(knownValue, value1, array2[i]))
console.log(output)

Merge multiple arrays together if not null

I am building a React App and am using Async Actions to make request to outside API's and bring in data into my app. I have 4 arrays that I need to merge together. Since I am using Async Actions the default values if theres no data is null. I want to check to see if the array is not null and if it has a value then merge it with the others into a single array. Once I have all the data into a single array I am going to use the includes method to see if any of the values are present in the array. Using the spread operator I don't think is going to work here as it will fail as null is not an iterable. Is there a way to do this with reduce to check through each of the 4 separate arrays make sure the value is not null and then combine them together into one array.
Your question leads you to the answer. :)
Essentially you are asking how to filter all non-array inputs and then combine (or concatenate) them together into a new array.
A couple of notes on the following approach:
For better stability in filtering, rather than using a blacklist (not null), use a whitelist (Array.isArray) to ensure only arrays are combined.
The spread operator can be used to then create an arguments list for a new array's concat method.
const arr1 = [1,2];
const arr2 = null;
const arr3 = [3,4];
const arr4 = [5];
const concat = (...arrays) => [].concat(...arrays.filter(Array.isArray));
console.log(concat(arr1, arr2, arr3, arr4));
For a bit of fun, if the combined array needs to be unique values (assuming simple types for values) then including a quick cast to a Set and back to an Array can make that happen:
const arr1 = [1,2];
const arr2 = null;
const arr3 = [3,4];
const arr4 = [4,5];
const concat = (...arrays) =>[].concat(...arrays.filter(Array.isArray));
const unique = (array) => [...new Set(array)];
const concated = concat(arr1, arr2, arr3, arr4);
const uniqued = unique(concated);
console.log({concated, uniqued});
Here is a one line solution (ES6).
At the first part, we merge all arrays, and then filter array elements - we include only "not null" values and exclude duplicates:
const arr1 = [1, null, 6, 'q'],
arr2 = null,
arr3 = [1, 1, null, 1],
arr4 = ['e', 'q', 6, 1, null];
const final = []
.concat(arr1, arr2, arr3, arr4)
.filter((item, i, arr) => item && arr.indexOf(item) === i);
console.log(final); // Expected output: [1, 6, "q", "e"]
var a = [1, 2, 3]
var b = null
var c = [...a||[], ...b||[]]
console.log(c)
If you assign your arrays to properties of an object obj, you can simply iterate over the object :
const a = ["a", "1"], b = null, c = ["c", 78], d = []
const obj = { a, b, c, d }
let res = []
for(let key in obj) {
res = res.concat(Array.isArray(obj[key]) ? obj[key] : []);
}
console.log(res)

How to insert an item into an array at a specific index (JavaScript)

I am looking for a JavaScript array insert method, in the style of:
arr.insert(index, item)
Preferably in jQuery, but any JavaScript implementation will do at this point.
You want the splice function on the native array object.
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).
In this example we will create an array and add an element to it into index 2:
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
You can implement the Array.insert method by doing this:
Array.prototype.insert = function ( index, ...items ) {
this.splice( index, 0, ...items );
};
Then you can use it like:
var arr = [ 'A', 'B', 'E' ];
arr.insert(2, 'C', 'D');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
Other than splice, you can use this approach which will not mutate the original array, but it will create a new array with the added item. It is useful, when you need to avoid mutation. I'm using the ES6 spread operator here.
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, newItem) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted item
newItem,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10)
console.log(result)
// [1, 10, 2, 3, 4, 5]
This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well:
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, ...newItems) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted items
...newItems,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10, 20)
console.log(result)
// [1, 10, 20, 2, 3, 4, 5]
Custom array insert methods
1. With multiple arguments and chaining support
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
this.splice.apply(this, [index, 0].concat(
Array.prototype.slice.call(arguments, 1)));
return this;
};
It can insert multiple elements (as native splice does) and supports chaining:
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]
2. With array-type arguments merging and chaining support
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
index = Math.min(index, this.length);
arguments.length > 1
&& this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
&& this.insert.apply(this, arguments);
return this;
};
It can merge arrays from the arguments with the given array and also supports chaining:
["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"
DEMO: http://jsfiddle.net/UPphH/
Using Array.prototype.splice() is an easy way to achieve it
const numbers = ['one', 'two', 'four', 'five']
numbers.splice(2, 0, 'three');
console.log(numbers)
Read more about Array.prototype.splice
If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript
Also here are some functions to illustrate both examples:
function insertAt(array, index) {
var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
return insertArrayAt(array, index, arrayToInsert);
}
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
return array;
}
Finally here is a jsFiddle so you can see it for yourself: http://jsfiddle.net/luisperezphd/Wc8aS/
And this is how you use the functions:
// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");
// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);
Solutions & Performance
Today (2020.04.24) I perform tests for chosen solutions for big and small arrays. I tested them on macOS v10.13.6 (High Sierra) on Chrome 81.0, Safari 13.1, and Firefox 75.0.
Conclusions
For all browsers
surprisingly for small arrays, non-in-place solutions based on slice and reduce (D,E,F) are usually 10x-100x faster than in-place solutions
for big arrays the in-place-solutions based on splice (AI, BI, and CI) was fastest (sometimes ~100x - but it depends on the array size)
for small arrays the BI solution was slowest
for big arrays the E solution was slowest
Details
Tests were divided into two groups: in-place solutions (AI, BI, and CI) and non-in-place solutions (D, E, and F) and was performed for two cases:
test for an array with 10 elements - you can run it here
test for an array with 1,000,000 elements - you can run it here
Tested code is presented in the below snippet:
jsfiddle
function AI(arr, i, el) {
arr.splice(i, 0, el);
return arr;
}
function BI(arr, i, el) {
Array.prototype.splice.apply(arr, [i, 0, el]);
return arr;
}
function CI(arr, i, el) {
Array.prototype.splice.call(arr, i, 0, el);
return arr;
}
function D(arr, i, el) {
return arr.slice(0, i).concat(el, arr.slice(i));
}
function E(arr, i, el) {
return [...arr.slice(0, i), el, ...arr.slice(i)]
}
function F(arr, i, el) {
return arr.reduce((s, a, j)=> (j-i ? s.push(a) : s.push(el, a), s), []);
}
// -------------
// TEST
// -------------
let arr = ["a", "b", "c", "d", "e", "f"];
let log = (n, f) => {
let a = f([...arr], 3, "NEW");
console.log(`${n}: [${a}]`);
};
log('AI', AI);
log('BI', BI);
log('CI', CI);
log('D', D);
log('E', E);
log('F', F);
This snippet only presents tested code (it not perform tests)
Example results for a small array on Google Chrome are below:
For proper functional programming and chaining purposes, an invention of Array.prototype.insert() is essential. Actually, the splice could have been perfect if it had returned the mutated array instead of a totally meaningless empty array. So here it goes:
Array.prototype.insert = function(i,...rest){
this.splice(i,0,...rest)
return this
}
var a = [3,4,8,9];
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");
Well, OK, the above with the Array.prototype.splice() one mutates the original array and some might complain like "you shouldn't modify what doesn't belong to you" and that might turn out to be right as well. So for the public welfare, I would like to give another Array.prototype.insert() which doesn't mutate the original array. Here it goes;
Array.prototype.insert = function(i,...rest){
return this.slice(0,i).concat(rest,this.slice(i));
}
var a = [3,4,8,9],
b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
You can use splice() for this
The splice() method usually receives three arguments when adding an element:
The index of the array where the item is going to be added.
The number of items to be removed, which in this case is 0.
The element to add.
let array = ['item 1', 'item 2', 'item 3']
let insertAtIndex = 0
let itemsToRemove = 0
array.splice(insertAtIndex, itemsToRemove, 'insert this string on index 0')
console.log(array)
I recommend using pure JavaScript in this case. Also there isn't any insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you. It's called splice...
Let's see what's splice()...
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
OK, imagine we have this array below:
const arr = [1, 2, 3, 4, 5];
We can remove 3 like this:
arr.splice(arr.indexOf(3), 1);
It will return 3, but if we check the arr now, we have:
[1, 2, 4, 5]
So far, so good, but how we can add a new element to array using splice?
Let's put back 3 in the arr...
arr.splice(2, 0, 3);
Let's see what we have done...
We use splice again, but this time for the second argument, we pass 0, meaning we don't want to delete any item, but at the same time, we add a third argument which is the 3 that will be added at second index...
You should be aware that we can delete and add at the same time. For example, now we can do:
arr.splice(2, 2, 3);
Which will delete two items at index 2. Then add 3 at index 2 and the result will be:
[1, 2, 3, 5];
This is showing how each item in splice work:
array.splice(start, deleteCount, item1, item2, item3 ...)
Here are two ways:
const array = [ 'My', 'name', 'Hamza' ];
array.splice(2, 0, 'is');
console.log("Method 1: ", array.join(" "));
Or
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
const array = [ 'My', 'name', 'Hamza' ];
array.insert(2, 'is');
console.log("Method 2 : ", array.join(" "));
Append a single element at a specific index
// Append at a specific position (here at index 1)
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Append at a specific position (here at index 3)
arrName[3] = 'newName1';
Append multiple elements at a specific index
// Append from index number 1
arrName.splice(1, 0, 'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where append start,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
Array#splice() is the way to go, unless you really want to avoid mutating the array. Given 2 arrays arr1 and arr2, here's how you would insert the contents of arr2 into arr1 after the first element:
const arr1 = ['a', 'd', 'e'];
const arr2 = ['b', 'c'];
arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']
console.log(arr1)
If you are concerned about mutating the array (for example, if using Immutable.js), you can instead use slice(), not to be confused with splice() with a 'p'.
const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];
Another possible solution, with usage of Array.reduce.
const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];
const insert = (arr, item, index) =>
arr.reduce(function(s, a, i) {
i === index ? s.push(item, a) : s.push(a);
return s;
}, []);
console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))
Even though this has been answered already, I'm adding this note for an alternative approach.
I wanted to place a known number of items into an array, into specific positions, as they come off of an "associative array" (i.e. an object) which by definition is not guaranteed to be in a sorted order. I wanted the resulting array to be an array of objects, but the objects to be in a specific order in the array since an array guarantees their order. So I did this.
First the source object, a JSONB string retrieved from PostgreSQL. I wanted to have it sorted by the "order" property in each child object.
var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';
var jsonb_obj = JSON.parse(jsonb_str);
Since the number of nodes in the object is known, I first create an array with the specified length:
var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);
And then iterate the object, placing the newly created temporary objects into the desired locations in the array without really any "sorting" taking place.
for (var key of Object.keys(jsonb_obj)) {
var tobj = {};
tobj[key] = jsonb_obj[key].abbr;
var position = jsonb_obj[key].order - 1;
sorted_array[position] = tobj;
}
console.dir(sorted_array);
Immutable insertion
Using the splice method is surely the best answer if you need to insert into an array in-place.
However, if you are looking for an immutable function that returns a new updated array instead of mutating the original array on insert, you can use the following function.
function insert(array, index) {
const items = Array.prototype.slice.call(arguments, 2);
return [].concat(array.slice(0, index), items, array.slice(index));
}
const list = ['one', 'two', 'three'];
const list1 = insert(list, 0, 'zero'); // Insert single item
const list2 = insert(list, 3, 'four', 'five', 'six'); // Insert multiple
console.log('Original list: ', list);
console.log('Inserted list1: ', list1);
console.log('Inserted list2: ', list2);
Note: This is a pre-ES6 way of doing it, so it works for both older and newer browsers.
If you're using ES6 then you can try out rest parameters too; see this answer.
Anyone who's still having issues with this one and have tried all the options in previous answers and never got it. I'm sharing my solution, and this is to take into consideration that you don't want to explicitly state the properties of your object vs the array.
function isIdentical(left, right){
return JSON.stringify(left) === JSON.stringify(right);
}
function contains(array, obj){
let count = 0;
array.map((cur) => {
if(this.isIdentical(cur, obj))
count++;
});
return count > 0;
}
This is a combination of iterating the reference array and comparing it to the object you wanted to check, converting both of them into a string, and then iterating if it matched. Then you can just count. This can be improved, but this is where I settled.
Taking profit of the reduce method as follows:
function insert(arr, val, index) {
return index >= arr.length
? arr.concat(val)
: arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}
So in this way we can return a new array (will be a cool functional way - more much better than using push or splice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.
I tried this and it is working fine!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
Index is the position where you want to insert or delete the element.
0, i.e., the second parameter, defines the number of elements from the index to be removed.
item contains the new entries which you want to make in the array. It can be one or more than one.
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
I have to agree with Redu's answer because splice() definitely has a bit of a confusing interface. And the response given by cdbajorin that "it only returns an empty array when the second parameter is 0. If it's greater than 0, it returns the items removed from the array" is, while accurate, proving the point.
The function's intent is to splice or as said earlier by Jakob Keller, "to join or connect, also to change.
You have an established array that you are now changing which would involve adding or removing elements...." Given that, the return value of the elements, if any, that were removed is awkward at best. And I 100% agree that this method could have been better suited to chaining if it had returned what seems natural, a new array with the spliced elements added. Then you could do things like ["19", "17"].splice(1,0,"18").join("...") or whatever you like with the returned array.
The fact that it returns what was removed is just kind of nonsense IMHO. If the intention of the method was to "cut out a set of elements" and that was its only intent, maybe. It seems like if I don't know what I'm cutting out already though, I probably have little reason to cut those elements out, doesn't it?
It would be better if it behaved like concat(), map(), reduce(), slice(), etc. where a new array is made from the existing array rather than mutating the existing array. Those are all chainable, and that is a significant issue. It's rather common to chain array manipulation.
It seems like the language needs to go one or the other direction and try to stick to it as much as possible. JavaScript being functional and less declarative, it just seems like a strange deviation from the norm.
I like a little safety and I use this:
Array.prototype.Insert = function (item, before) {
if (!item) return;
if (before == null || before < 0 || before > this.length - 1) {
this.push(item);
return;
}
this.splice(before, 0, item);
}
var t = ["a", "b"]
t.Insert("v", 1)
console.log(t)
You can do it with array.splice:
/**
* #param arr: Array
* #param item: item to insert
* #param index: index at which to insert
* #returns array with the inserted element
*/
export function _arrayInsertAt<T>(arr: T[], item: T, index: number) {
return arr.splice(index, 0, item);;
}
Doc of array.slice
Here's a working function that I use in one of my applications.
This checks if an item exists:
let ifExist = (item, strings = [ '' ], position = 0) => {
// Output into an array with an empty string. Important just in case their isn't any item.
let output = [ '' ];
// Check to see if the item that will be positioned exist.
if (item) {
// Output should be equal to an array of strings.
output = strings;
// Use splice() in order to break the array.
// Use positional parameters to state where to put the item
// and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
output.splice(position, 0, item);
}
// Empty string is so we do not concatenate with comma or anything else.
return output.join("");
};
And then I call it below.
ifExist("friends", [ ' ( ', ' )' ], 1)} // Output: ( friends )
ifExist("friends", [ ' - '], 1)} // Output: - friends
ifExist("friends", [ ':'], 0)} // Output: friends:
Here is the modern (Typescript functional) way:
export const insertItemInList = <T>(
arr: T[],
index: number,
newItem: T
): T[] => [...arr.slice(0, index), newItem, ...arr.slice(index)]
I do it like so:
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
const list = [1, 2, 3, 4, 5, 6];
const newList = insert('a', list, 2);
console.log(newList.indexOf('a') === 2);
Here's a simple function that supports inserting multiple values at the same time:
function add_items_to_array_at_position(array, index, new_items)
{
return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}
Usage example:
let old_array = [1,2,5];
let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);
console.log(new_array);
//Output: [1,2,3,4,5]
var array= [10,20,30,40]
var i;
var pos=2; //pos=index + 1
/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/
var value=5
//value to insert
//Initialize from last array element
for(i=array.length-1;i>=pos-1;i--){
array[i+1]=array[i]
}
array[pos-1]=value
console.log(array)
Multi purpose for ARRAY and ARRAY OF OBJECT reusable approach
let arr = [0,1,2];
let obj = [{ name: "abc"},{ name: "xyz"},{ name: "ijk"} ];
const addArrayItemAtIndex = ( array, index, newItem ) => {
return [...array.slice(0, index), newItem, ...array.slice(index)];
}
// For Array
console.log( addArrayItemAtIndex(arr, 2, 159 ) );
// For Array of Objects
console.log( addArrayItemAtIndex(obj, 0, { name: "AMOOS"} ) );

Categories