How to remove first array element using the spread syntax - javascript

So I have an array, ex. const arr = [1, 2, 3, 4];. I'd like to use the spread syntax ... to remove the first element.
ie. [1, 2, 3, 4] ==> [2, 3, 4]
Can this be done with the spread syntax?
Edit: Simplified the question for a more general use case.

Sure you can.
const xs = [1,2,3,4];
const tail = ([x, ...xs]) => xs;
console.log(tail(xs));
Is that what you're looking for?
You originally wanted to remove the second element which is simple enough:
const xs = [1,0,2,3,4];
const remove2nd = ([x, y, ...xs]) => [x, ...xs];
console.log(remove2nd(xs));
Hope that helps.

Destructuring assignment
var a = [1, 2, 3, 4];
[, ...a] = a
console.log( a )

Is this what you're looking for?
const input = [1, 0, 2, 3, 4];
const output = [input[0], ...input.slice(2)];
After the question was updated:
const input = [1, 2, 3, 4];
const output = [...input.slice(1)];
But this is silly, because you can just do:
const input = [1, 2, 3, 4];
const output = input.slice(1);

You could use the rest operator (...arrOutput) with the spread operator(...arr).
const arr = [1, 2, 3, 4];
const [itemRemoved, ...arrOutput] = [...arr];
console.log(arrOutput);

Related

How to duplicate indexes in array with numbers of second array, resulting third array in JS

I have an array of products amount, and another array of products ID's.
I'm trying to do something like this:
arrayOfAmount = [2,3,4]
arrayOfId = [1,2,3]
resulting the third array of ID's:
arrayOfProducts = [1,1,2,2,2,3,3,3,3]
how can I do that?
thank you in advance!
You can try this:
let arrayOfAmount = [2,3,4]
let arrayOfId = [1,2,3]
console.log(arrayOfId.flatMap((x,i)=>Array(arrayOfAmount[i]).fill(x)))
Here is a version how you could do this using the map and flat and fill methods of arrays. I added some comments to help understanding what the code does:
const arrayOfAmount = [2, 3, 4];
const arrayOfId = [1, 2, 3];
const arrayOfProducts = arrayOfId.map((id, index) => {
// get how often an id should be in the array
const length = arrayOfAmount[index];
// create an array with the length
const array = Array(length);
// insert the ID to every index of the array
return array.fill(id);
})
// and finally flat, so that the array doesn't look like: [[1, 1], [2, 2, 2], [3, 3, 3, 3]]
.flat();
console.log(arrayOfProducts);
A short version would be:
const arrayOfAmount = [2, 3, 4];
const arrayOfId = [1, 2, 3];
const arrayOfProducts = arrayOfId.map((id, index) => Array(arrayOfAmount[index]).fill(id))
.flat();

Putting array elements in another by spread method (but a little differently)

I used another (my) way to store the elements of some array in another as a spread method.
I used join method for this way, but the array contains only one.
Here's my code:
const arr = [1, 2, 3];
const newArray = [eval(arr.join(', ')), 4, 5]
console.log(newArray) // [3, 4, 5]
Try this:
const arr = [1, 2, 3];
const newArray = [...arr, 4, 5];
console.log(newArray);
You can use concat for that.
The concat() method will join two (or more) arrays and will not change the existing arrays, but instead will return a new array, containing the values of the joined arrays.
const arr = [1, 2, 3];
const newArray = arr.concat([4, 5]);
console.log(newArray)
Another option is to use spread syntax (...) (introduced in ES6)
const arr = [1, 2, 3];
const newArray = [...arr, ...[4, 5]];
console.log(newArray)

How to compare two arrays and add/remove elements depending on their difference?

Let's say I have two arrays, where array1 is always changing:
First case:
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 3]
How can I compare them and add 4 and 5 into array2?
I am getting the difference between them doing:
let difference = array1.filter(x => !array2.includes(x));
and then doing array2.push(difference), so array2 is now equal to array1, right?
Second case:
array1 = [1, 2, 8, 9]
array2 = [1, 2, 3]
So now I need to remove 3 from array2, and add 8 and 9, how can I do this?
EDIT: I need this because I'm getting array1 from a server(they are chats) and it's dynamically changing every 5 sec, and this is problem. I need to keep the elements I already have so they won't "update" and only change the one getting deleted or added. Hope this makes sense.
First case will not work as aspectedlooking at the code,
to achive what you want you have to write:
difference.forEach((x) => array2.push(x));
instead of:
array2.push(difference)
for the second one if you want to remove a record in array2 because is missing in array1 you need to control each value of array2 in array1 and remove if not exists by ID
var array1 = [1, 2, 8, 9];
var array2 = [1, 2, 3];
//here i build difference2 collecting the value of array2 that miss on array1
let difference2 = array2.filter((x) => !array1.includes(x));
//here with splice and indexOf i remove every value collected before
difference2.forEach((x) => array2.splice(array2.indexOf(x), 1));
//following code is to add the 8 and 9
let difference = array1.filter((x) => !array2.includes(x));
difference.forEach((x) => array2.push(x));
console.log(array2);
//the result [1,2,8,9]
let array1 = [1, 2, 3, 4, 5];
let array2 = [1, 2, 3];
let filteredArray = array2.filter((a) => array1.includes(a));
let secFilteredArray = array1.filter((a) => !filteredArray.includes(a));
console.log(filteredArray.concat(secFilteredArray));
You could take a Set and delete seen items and add the rest to the array.
const
array1 = [1, 2, 8, 9],
array2 = [1, 2, 3],
set1 = new Set(array1);
let i = array2.length;
while (i--) if (!set1.delete(array2[i])) array2.splice(i, 1);
array2.push(...set1);
console.log(array2);
Just use another filter and combine the two arrays.
const array1 = [1, 2, 8, 9];
let array2 = [1, 2, 3];
const inArrOne = array1.filter(x => !array2.includes(x));
const inBothArr = array2.filter(x => array1.includes(x));
array2 = [...inBothArr, ...inArrOne];
console.log(array2);
I would avoid much built-in or third party compare functions since I am not sure what I am dealing with. This could be refactored and optimized more if the array1 is guaranteed to have an ordered list.
let localArray = [1, 2, 3, 4, 5],
lastServerArray = [];
/**
* Compares "fromArr" to "targetArr"
* #param fromArr Array of elements
* #param targetArr Array of elements
* #returns List of elements from "fromArr" that do not happen in "targetArr"
*/
const compArr = (fromArr, targetArr) => {
const result = [];
for (let i = 0, len = fromArr.length; i < len; i++) {
const elem = fromArr[i],
targetIdx = targetArr.indexOf(elem);
if (!~targetIdx && !~result.indexOf(elem)) {
// Element do not exist in "targetArr" and in current "result"
result.push(elem);
}
}
return result;
}
const updateLocalArray = (serverArray = []) => {
if (JSON.stringify(lastServerArray) === JSON.stringify(serverArray)) {
console.log('Nothing changed from server, skip updating local array');
return localArray;
}
lastServerArray = serverArray;
const notExistentLocalElems = compArr(serverArray, localArray), // Elements that do not exists in local array
notExistentServerElems = compArr(localArray, serverArray); // Elements that do not exists in server array
// Do something to those "notExistentLocalElems" or "notExistentServerElems"
// ---
// Sync server array to local array
// Remove elements that is not on server.
localArray = localArray.filter(elem => !~notExistentServerElems.indexOf(elem));
console.log('These elements removed from localArray', notExistentServerElems);
// Append elements that is on server.
localArray.push(...notExistentLocalElems);
console.log( 'These elements added into localArray', notExistentLocalElems);
return localArray;
}
updateLocalArray([1, 2, 3]);
console.log(`1. server sends [1, 2, 3] -- local becomes`, localArray);
updateLocalArray([3, 4, 5, 6]);
console.log(`2. server sends [3, 4, 5, 6] -- local becomes`, localArray);
updateLocalArray([5, 5, 4, 2, 7]);
console.log(`3. server sends [5, 5, 4, 2, 7] -- local becomes`, localArray);
updateLocalArray([0, 0, 1, 2]);
console.log(`4. server sends [0, 0, 1, 2] -- local becomes`, localArray);
You could do like this if you want to mutate array2:
let array1 = [1, 2, 8, 9];
let array2 = [1, 2, 3];
let valuesToAdd = array1.filter(x => !array2.includes(x));
let indexesToDelete = Object.entries(array2).filter(([, x]) => !array1.includes(x)).map(([i]) => i);
// Reverse iteration to preserve indexes while removing items
indexesToDelete.reverse().forEach(i => array2.splice(indexesToDelete[i], 1));
array2.push(...valuesToAdd);
console.log(array2);

How to get which do not intersect value between 2 Array with Lodash?

How to get which do not intersect value between 2 Array with Lodash?
Expected:
const arr1 = [1, 2, 3]
const arr2 = [2, 3, 4]
console.log(unintersection(arr1, arr2))
Output
[1, 4]
Use _.xor() to find the symmetric difference - the numbers that are in one of the arrays, but not both:
const arr1 = [1, 2, 3]
const arr2 = [2, 3, 4]
const result = _.xor(arr1, arr2)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

How to get the head and rest of an array in JavaScript?

I have an array and would like to get its head and the rest. How do I do this using a destructuring assignment? Is this even possible?
If the array has only two elements, it's pretty easy:
const [head, rest] = myArray;
But what if it contains more than two entries?
You can use spread syntax for that.
const [head, ...rest] = myArray;
var myArray = [1, 2, 3, 4, 5, 6];
const [head, ...rest] = myArray;
console.log(head);
console.log(rest);
Thay way:
const [head, ...rest] = myArray;
With the spread syntax ..., all other items goes into the rest array.
const [head, ...rest] = [1, 2, 3, 4, 5];
console.log(head);
console.log(rest);
You can do like this
const [car, ...cdr] = [1, 2, 3, 4, 5];
console.log(car); // 1
console.log(cdr); // [2, 3, 4, 5]
For more details, refer this link
Hope this helps :)
Accoding to Destructing assignment (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) :
var x = [1, 2, 3, 4, 5];
var [y, z] = x;
console.log(y); // 1
console.log(z); // 2

Categories