Remove multiple array from other array jquery - javascript

I Have 2 array like this
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
how can I remove values in array from arr?
I want to obtain
arr = ["9138214"]
Maybe I can use splice() ?

You can use Array.forEach() to loop over to the array of items and then check that each item exist in array array. If so use splice(). Use simple function and indexOf() as it will work in old browsers and also in IE.
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "91382142"];
var i = arr.length;
while (i--) {
if (array.indexOf(arr[i]) !== -1) {
arr.splice(i, 1);
}
}
console.log(arr);

You can use .filter() for that.
Here is an example:
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "9138238"];
arr = arr.filter(e => !array.includes(e));
console.log(arr)
The code above just filters the arr array and keeps only elements that are not present in the array. The .includes() function that I've used works on these arrays because they contain strings, if you're dealing with objects, you need to find some other way of checking if array contains the element.

If you want to lodash, this can be easily done by the difference function:
https://lodash.com/docs/4.17.10#difference
import {difference} from 'lodash';
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
console.log(difference(arr, array));

Related

How to get unique values from two 2D arrays in JavaScript

I am trying to get unique values from two arrays which looks like that:
array[{A,B,C},{C,D,E},{1,3,2},....]
both looks the same.
I tried to add them using concat and the get unique values from looping.
So I ended up with this:
function uniqueValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = ss.getSheetByName("arr1");
const array1 = srcSheet.getRange(1, 1, srcSheet.getLastRow(), srcSheet.getLastColumn()).getValues();
var srcSheet1 = ss.getSheetByName("arr2");
const array2 = srcSheet1.getRange(1, 1, srcSheet1.getLastRow(), srcSheet1.getLastColumn()).getValues();
var dodaj = array1.concat(array2);
for (var i=0; i<dodaj.length; i++) {
var listI = dodaj[i];
loopJ: for (var j=0; j<dodaj.length; j++) {
var listJ = dodaj[j];
if (listI === listJ) continue;
for (var k=listJ.length; k>=0; k--) {
if (listJ[k] !== listI[k]) continue loopJ;
}
dodaj.splice(j, 1);
}
}
var result = ss.getSheetByName("test").getRange(2, 5, dodaj.length, 3).setValues(dodaj);
//Logger.log(dodaj);
}
It was working well when array looked like this array[{A,B},{C,D}] but with three elements it started to return duplicates as well... I have no idea what can be wrong.
If I understand you correctly, you want to retrieve the unique rows from the values in arr1 and arr2. That is to say, you want to remove duplicate inner arrays from dodaj.
After using concat to merge the two arrays, you could do the following:
Use JSON.stringify() to transform each inner array to a string, in order to compare them without iterating through them.
Use the Set constructor and the spread syntax in order to remove the duplicate strings (see this answer).
Transform the strings back to arrays with JSON.parse().
Code snippet:
var dodaj = array1.concat(array2);
dodaj = [...new Set(dodaj.map(JSON.stringify))].map(JSON.parse);
var result = ss.getSheetByName("test").getRange(2, 5, dodaj.length, dodaj[0].length).setValues(dodaj);

Add array inside array in Javascript

How do I push array into a new Array.
For example
var arr = ['one','two','three'];
var newArr = [];
Now I want newArr[0] = ['one','two','three']
I have tried using push function but it pushes all the elements of arr into newArr. I want to push the entire arr as it is in newArr
var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array
You can write:
newArr[0] = ['one','two','three'];
And this will work. Or use variable:
newArr[0] = arr;
Also, array methods push or unshift will the same way in your situation work:
newArr.push(arr);
Others have answered, so I guess your question is not really clear.
As you put your question, first and only element of newArray should be the arr array, then you use
newArr.push(arr);
as Mitya and Tiij7 said.
However, maybe you meant you want to join (concat) 2 arrays in a new array? Then you would use:
var arr3 = [].concat(arr, newArr);
or
var arr3 = [...arr, ...newArr];
Or you just wanted to clone the initial array? Then use
var newArr = [...arr];

Array.slice using index number contained in another array

I have two arrays.I'm trying to remove some elements from [arr] at index numbers in [removeIndex].
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length;i++){
arr.splice(removeIndex[i],1);
}
console.log(arr)
// output Array(5) [ 1, 1, 0, 1, 1 ]
//expected [ 1,1,1,1,1]
Both the 0's are at arr[2] and arr[3] position and should get removed,however the above code doesnt work.I suspect it has to do with the loop re-arranging the index numbers.Any alternate solution?
You definitely suspect correctly about why this is happening. The easiest way I can think of to do what you're after is to use the not-often-used second argument to the callback function passed to the filter method, which takes an element's index:
arr = arr.filter((elt, index) => removeIndex.indexOf(index) == -1);
You can use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes()
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Pass index as the second parameter to check whether that index includes or not in removeIndex. Return the element only if the current index does not exist in removeIndex array:
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
arr = arr.filter((i,idx) => !removeIndex.includes(idx));
console.log(arr); //[ 1,1,1,1,1]
I would use filter and come up with this clean code:
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
var newArr = arr.filter(el => el !== 0);
console.log(newArr);
// [1,1,1,1,1]
As stated in the comments, you mutate the array so the next time you loop through the array it's items will be changed and you won't have the same items at the same indexes. There is a fairly simple solution for your particular example :
var removeIndex = [2,3].sort(); // This won't work with [3,2] for example
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length; i++){
arr.splice(removeIndex[i] - i, 1);
}
console.log(arr)
But I'd suggest using an immutable solution with .filter for example, like suggested in the comments

Convert array with 5 items into array with 1 item

I have an array called 'xxx' with contains 5 items.
I would like to convert it in to a single array with the name newTableData[].
What is the best way to do this?
You can assign array with 5 elements to the zeroth element of second array
var newArray = [];
newArray[0] = existingArray;
var cars = ["Audi", "Volvo", "BMW", "Bentley", "Maruti"];
var newArray = [];
newArray[0] = cars;
console.log(newArray);
For flattening your initial array, you can just do
const flattenedArray = [].concat.apply([], oldArray);
const newArray = [flattenedArray];
If I'm right, the problem is that you have an Array of Arrays of TableItems. Just use a reduce and concat:
xxx.reduce((acc, arrayWithTableItem) => acc.concat(arrayWithTableItem), []);
This way you take advantage of the fact that concat flattens a single level down, so from this:
[[TableItem], ...[TableItem]]
you end up with
[TableItem, ...TableItem]
It's easy peas from there
[xxx.reduce((acc, x) => acc.concat(x), [])]
if you are using ES6+ you can use array destructuring ...
cont newTableData[0] = [...xxx];

array.splice() gives error TypeError: arr.splice is not a function(…)

var arr = document.querySelectorAll("a[href*='somestring']")
Returns what looks like an array in the console. Square braces [] and arr.length = 7.
Screen below. Why won't splice() work on my array?
The object returned from querySelectorAll is a NodeList, which is Array-like, yet not an actual array.
Try this to convert to an array:
[].slice.call(document.querySelectorAll("a[href*='somestring']"));
https://developer.mozilla.org/en-US/docs/Web/API/NodeList
HTMLCollection and NodeList objects do not have a splice method and do not inherit from Array.prototype.
Furthermore, you can't simply invoke a splice on them as they're not designed to be modified even though they are Array-like.
First, convert them to a true Array.
var arr = document.querySelectorAll("a[href*='somestring']"); // NodeList
arr = Array.prototype.slice.call(arr); // Array
arr.splice(2, 2); // splicing an Array
document.querySelectorAll("a[href*='somestring']") return an object not array.
try to convert it to an array:
var arr = document.querySelectorAll("a[href*='somestring']");
var a = [];
for(var i =0;i<arr.length ; i++){
a[i] = arr[i];
}
a.splice()//now you can use a as an array

Categories

Resources