Convert array with 5 items into array with 1 item - javascript

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];

Related

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];

Remove multiple array from other array jquery

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));

change format of a array javascript

How can I change the format of the array? the idea is to place the array2 equal to the array1, I mean the format of square brackets and commas.
that is, change the ":" with "," and the {} with []
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}]
The most appropriate way to do this is probably using the map() method. Using this, you're constructing a new array by manipulating each item of an original array. Learn more here.
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}];
var array1 = array2.map(function (item) {
var key = Object.keys(item)[0];
var value = item[key];
return [key, value];
});
console.log(array1);
// returns [["Sep", 687918], ["Nov", 290709], ["Dic", 9282], ["Ene", 348529]]
This work for you?
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var array2 = {};
array1.forEach(function(element){
array2[element[0]]=element[1];
});
"I mean the format of square brackets and commas"
Square brackets says, that it is an array, and array elements should be separated by commas. Actually, you want to convert the array of arrays to the array of objects. Here is short ES6 solution:
var array1 = [["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var newArray = [];
array1.forEach(item => newArray.push({[item[0]]: item[1]}))
console.log(newArray)
You can do this by using the array .reduce method:
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2 = array1.reduce((arr2, current) => {
arr2.push({[current[0]]: current[1]});
return arr2
}, []);
console.log(array2)

How should i get array of array in javascript as a single value array?

If a have an array in javascript like:
[[2,3,4],"data","payload",[name1,name2,name3]]
how should I get all the values as a single array like
Result array should be like this :
[2,3,4,"data","payload",name1,name2,name3]
You can flatten it with .concat().
var data = [[2,3,4],"data","payload",["name1","name2","name3"]];
console.log([].concat(...data));
Any Array argument passed to .concat() will be flattened into the result.
This also uses the "spread syntax", which is only available in newer engines. Use .apply() for legacy support.
var data = [[2,3,4],"data","payload",["name1","name2","name3"]];
console.log(data.concat.apply([], data));
Use reduce() for this.
const array = [[2,3,4],"data","payload",["name1","name2","name3"]]
const flattenedArray = array.reduce((a, b) => a.concat(b), [])
console.log(flattenedArray)
MDN reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You could use concat() to concatenate all the items in your main array into one big array, which I understand is what you're after :
var my2dArray = [[2,3,4],"data","payload",[name1,name2,name3]];
var my1dArray = [];
for(var i = 0; i < my2dArray.length; i++)
{
my1dArray = my1dArray.concat(my2dArray[i]);
}
console.log(my1dArray); // will be [2,3,4,"data","payload",name1,name2,name3]
You can use the concat():
var array = [
[2, 3, 4],
"data",
"payload",
['name1', 'name2', 'name3'],
]
var newArr = [].concat.apply([], array);
console.log(newArr);

How to create sub array from array

I have large data structure to manipulate and I have some problems sorting similar data into sub array.
var arr = [2016-12-16, 2016-12-16, 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-18, 2016-12-18, 2016-12-19];
I wanna sort like this.
[[2016-12-16, 2016-12-16], [ 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-17],[2016-12-18, 2016-12-18] [2016-12-19]]
Array#reduce the array into an array of arrays by using a object as a hash:
var arr = ['2016-12-16', '2016-12-16', '2016-12-17', '2016-12-17', '2016-12-17', '2016-12-17', '2016-12-18', '2016-12-18', '2016-12-19'];
var result = arr.reduce(function(r, item) {
(r.hash[item] || (r.hash[item] = r.arr[r.arr.push([]) - 1])).push(item);
return r;
}, { arr: [], hash: {} }).arr;
console.log(result);
The easiest way to do this is with a dictionary (which JS objects naturally act as).
var datesArray = [ "2016-12-16", "2016-12-16", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-18", "2016-12-18", "2016-12-19" ]; //I've corrected the syntax for this to make each date a string, rather than a sequence of subtractions
var datesCount = {};
datesArray.forEach(function(date){
if(!datesCount[date])
datesCount[date] = []
datesCount[date].push(date);
});
At this point, you have a set of group arrays, each containing every instance of a particular date. You can iterate over it with Object.getOwnPropertyNames and put each array into the larger array OR you could just use it directly.
try to divide the code to sub problems-
first, convert all element to strings (before writing a function).
copy the array to manipulate without changing original.
sort elements.
identify repeated elements.
create sub arrays for repeated elements.
this a code I've written for a differend purpose and modified it for the explanation.
there might be more effient ways to write it, i'm still learning..
const dateStringSort = (array) => {
//assign to a new array - wont change exist array
const arr = [].concat(array);
//sort elements
arr.sort();
//identify repeated elements and group them to sub arrays.
const arr1 = []; //assign another array to prevent inifinty loops
while (arr.length>0){
let i = arr[0];
let filtered = arr.filter(item=>item===i);//return new array with all reapeted elements
arr1.push(filtered); //push the filtered array to new array as a sub array
arr.splice(0,(filtered.length)); //delete all the repeated elements from arr to prevent double sub araays
};
//return new array
return arr1;
};
//run function
const originArray = ["2016-12-16", "2016-12-16", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-18", "2016-12-18", "2016-12-19"];
const newArray = dateStringSort(originArray);

Categories

Resources