How to add an element at the end of each array? - javascript

I have an array which has thousands of rows from google spreadsheet for example:-
var array = [[1,2,3,4],[2,3,4,1],[1,4,5,6]......]
I want to add an element lets say "x" end of every array. I need a solution like this :-
[[1,2,3,4,x],[2,3,4,1,x],[1,4,5,6,x]......]
How can I achieve this.

#Askish has a great answer, but I would like to provide an alternative.
This approach mutates the arrays instead of creating new ones
var array = [[1,2,3,4],[2,3,4,1],[1,4,5,6]];
array.forEach(e => e.push("x"));
console.log(array);

var array = [[1,2,3,4],[2,3,4,1],[1,4,5,6]];
var newArray = array.map(x => [...x, 'x']);
console.log(newArray);

Related

How do I add the same element to an array multiple times?

I'm making shopping cart,and I am a little bit confused. There is a counter which counts number of current product. For example: the user can buy 5 book or more. So , I need to make a function which adds the element аs many times as the user will select it.
I made something like this:
[...state.shoppingCart, new Array(state.booksNumber).fill({...action.book})]
But of course it makes a new array in array... So how can I just add elements to an array without deleting old elements or creating a new array inside the array?
I need a functional way, no loops.
const newArray = new Array(state.booksNumber).fill({...action.book})
[...state.shoppingCart, ...newArray]
Simply use the spread syntax again:
[...state.shoppingCart, ...new Array(state.booksNumber).fill({...action.book})]
That will spread the new array into the existing array.
You can use the concat method
const a = new Array([1,3,4]).concat([1,3,4])
console.log(a)
This will add the elements into the array.
Or you can try with spread operator.
const arr=[1,2,3,4]
const a = new Array([1,3,4,.... arr]);
console.log(a)
You are missing the spread operator inside the returning array for the new Array you created.
Adding the spread operator allows you to merge/concat both array items.
For example:
const arrayOne = [1,2,3];
const arrayTwo = [4,5,6];
const mergedArrays = [...arrayOne, ...arrayTwo] //[1,2,3,4,5,6]
Also assuming action.book is an object you want to add multiple times inside of the new Array() you've created, there is no need to spread it as it will fill the array with each object.
This function might help out with what you are looking for:
const addMultipleItems = (action) => {
const items = new Array(state.booksNumber).fill(action.book);
return [...state.shoppingCart, ...items];
}

How to search in nested JSON data in vuejs?

I have nested JSON data like:
[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]
I want to filter the JSON by province_id and put it in another variable. Is there any solutions in VueJS such as Vue.filter(); ?
I know we have "linq" which does the job but I do not want to use it.
what you're looking for is the javascript Array's filter() function. You should definitely spend some time getting familiar with filter, along with others like map and reduce. It'll make slicing and dicing your data much easier.
var serializedData = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var data = JSON.parse(serializedData);
var provinceAbc = data.filter(d => d.province_id === 'ABC');
That line will get you all objects where its province_id is "ABC"
Also, since you mentioned "linq" in your post, filter() is like IEnumerable.Where(), and map() is like IEnumerable.Select() in .NET Linq terms
I think this will work for you:
var nestedJson = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var array = JSON.parse(nestedJson);
array = array.map(e => e["province_id"]);
console.log(array);

Filter array if element is present in another array based on value

I have an object array like this:
var objectArray = [{id_5:"100"},
{id_1:"300"},
{id_2:"500"},
{id_4:"700"},
{id_3:"200"}];
And a normal array like this:
var normalArray = ["id_2","id_5","id_4"];
I want to subtract every element from the objectArray if there's a matching ID in the normalArray. I then want to order the newly created array by the object's value (lowest value being first).
So for the above example the result would be:
var newObjectArray = [{id_3:"200"},
{id_1:"300"}];
Is it possible to do this without jQuery?
I've seen similar questions like this one: Removing object from one array if present in another array based on value but I haven't been able to find an answer that works. Is it possible to do a compare and remove like this while still keeping the key:value pairs intact? Thanks in advance for any help with this!
You should use filter method, which accepts as parameter a callback function.
Also, you have to use Object.keys() method in order to get the key of each object in objectArray.
To check if an element from objectArray doesn't appear in objectArray, you should use indexOf() method.
To achieve the sorted array, you have to use sort() method.
var objectArray = [{id_5:"100"},
{id_1:"300"},
{id_2:"500"},
{id_4:"700"},
{id_3:"200"}];
var normalArray = ["id_2","id_5","id_4"];
var newArray=objectArray.filter(function(item){
return normalArray.indexOf(Object.keys(item)[0]) == -1;
}).sort(function(a,b){
return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});
console.log(newArray);
You can first use filter() to remove object with key from other array and then sort to sort result array by objects value.
var objectArray = [{id_5:"100"},{id_1:"300"},{id_2:"500"},{id_4:"700"},{id_3:"200"}];
var normalArray = ["id_2","id_5","id_4"];
var newArray = objectArray
.filter(e => !normalArray.includes(Object.keys(e)[0]))
.sort((a, b) => a[Object.keys(a)[0]] - b[Object.keys(b)[0]])
console.log(newArray)

How to store number of object element of array in another array?

im trying to store some object element from one array to another so lets say i have this array of objects
var Array = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
and i want to store the first two object in this array to another array so it would like be
var SubArray =[{name:'Fadi'},{name:'Joseph'}];
thanks in advance for any help.
You can use slice method for this:
var SubArray = Array.slice(0,2);
Please note that Array is reserved JS global object. You need to use different name for that variable. So your code should be for example:
var MyArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var SubArray = MyArray.slice(0,2);
If you need conditional logic you want Array.filter(). If you know you always want the items by index then use slice as in antyrat's answer.
var originalArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var subArray = originalArray.filter(function(obj,index) {
return obj.name=="Fadi" || obj.name=="Joseph";
})

Concatenating html object arrays with javascript

I'm attempting to merge two arrays made up of html objects. For some reason using .concat() will not work for me.
Here's a simple pen to demonstrate the problem: http://codepen.io/anon/pen/kIeyB
Note: I tried searching for something remotely similar but found nothing that answered my question.
I figure you can do this the ole fashion way using for-loops but I rather not re-invent the wheel.
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
//alert(items.length);
var items2 = x.getElementsByClassName("two");
//alert(items2.length);
items = items.concat(items2);
//alert(items.length);
items and items2 are nodeList or HTMLCollection objects, not arrays. They do not contain a .concat() method. They have a .length property and support [x] indexing, but they do not have the other array methods.
A common workaround to copy them into an actual array is as follows:
// convert both to arrays so they have the full complement of Array methods
var array1 = Array.prototype.slice.call(x.getElementsByClassName("one"), 0);
var array2 = Array.prototype.slice.call(x.getElementsByClassName("two"), 0);
This can be also be done like this:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
The allitems variable will be a single javascript Array containing all elements with class one & two.
What you have are HTMLCollections, which although behave like arrays, but are not arrays. See here: https://developer.mozilla.org/en/docs/Web/API/HTMLCollection:
..A collection is an object that represents a lists of DOM nodes..
In your case, you could concatenate these objects together into a new array:
var itemsnew;
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
var items2 = x.getElementsByClassName("two");
itemsnew = Array.prototype.concat.call(items, items2);
Now, if you:
console.log(itemsnew);
Will return:
[HTMLCollection[1], HTMLCollection[1]]
And:
console.log(itemsnew[0][0]);
Will return:
<div class="one"></div>
document.getElementsByClassName doesn't return an array.
It returns NodeList which has length property.

Categories

Resources