I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)
Related
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];
Let's say I have two array's
let array1 = ["H","E","", "","O","","","R","L","D"];
let array2 = ["","","L","L","","W","O","","",""];
I want to merge them such that they would then contain:
array3 = ["H","E","L", "L","O","W","O","R","L","D"];
How would I achieve this?
To be more clear I have a target array which is array3 an empty array and then I'm generating random characters and if they match array3 adding them to the blank array in the specific position with react state. It is just not storing the position and character each time but just changing it. SO my idea is to set the state such that I merge the current state with the new characters that are found.
TLDR:- Brute forcing Hello World meme.
You can use Array.prototype.map() to create a new array array3 out of iterating over array1 and get the l (letters) and if any l evaluates to falsey then get the letter at the same i (index) in the array2.
Note that instead of declaring your arrays with let you should always use const because it makes code easier to read within its scope, and const variable always refers to the same object.
Code example:
const array1 = ["H","E","", "","O","","","R","L","D"];
const array2 = ["","","L","L","","W","O","","",""];
const array3 = array1.map((l, i) => l || array2[i]);
console.log(array3);
Try it:
let arr1 = ["H","E","", "","O","","","R","L","D"];
let arr2 = ["","","L","L","","W","O","","",""];
let arr3 = [];
arr1.forEach((val, index) => {
if (val === '') {
arr3[index] = arr2[index];
} else {
arr3[index] = val;
}
});
console.log(arr3);
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)
I have a result set which is an array of objects. I need to clone this so I can make changes to it, without touching the original data.
var data = w2ui.grid.records,
exclude = Array('recid', 'w2ui'); // Exclude these data points from the pivot
// Modify our tempData records to remove HTML
$.each(data, function(key, value) {
$.each(value, function(_key, _value) {
if(jQuery.inArray(_key, exclude) != -1) {
delete data[key][_key];
}else{
data[key][_key] = $('<div>'+_value+'</div>').text(); // <div></div> for those which are simply strings.
}
});
});
In this example, I created a variable called data and set it to my "Source Data".
I expected to be able to make changes to this new data variable but it appears that when making changes to it, the source data is being changed (w2ui.grid.records).
Is there a proper way to clone this set so I can have a new instance of the data to modify?
EDIT
Deep clone use JSON.parse(JSON.stringify(arr));
Shallow clone Use slice(0);
var arr = [{'obj1':1}, {'obj2':2}];
var clone = arr.slice(0);
console.log(clone);
var arr = [{'obj1':1}, {'obj2':2}]
var clone = JSON.parse(JSON.stringify(arr));
console.log(clone);
ES6:
If you want to have cloned objects too, you have to spread array and objects:
const newArrayOfObjects = [
...originalArrayOfObject
].map(i => ({ ...i}));
Since you are using jquery you can try extend:
var arr = [{'obj1':1}, {'obj2':2}];
var clone = jQuery.extend(true, [], arr);
clone[0]['obj1']=10;
console.log(clone);
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Lodash has a method specifically for this called clonedeep. There's a standalone package for it if you don't want to pull in the entire library:
https://www.npmjs.com/package/lodash.clonedeep
This is because an array is held as a pointer, so setting a new variable just points to the same array.
The easiest way I know of is with slice...
var data = w2ui.grid.records.slice(0);
This creates a new array with all of the original values in, because you're slicing from the first one (0).
If you need a deep clone, because your array contains objects/arrays too, try this...
https://github.com/pvorb/clone
below code worked for me to deep Clone an array of object which does not have any function stored in them.
const deepClone = input => {
if (typeof input !== 'object') return input;
const output = Array.isArray(input) ? [] : {};
const keys = Object.keys(input);
keys.forEach(key => {
output[key] = deepClone(input[key]);
});
return output;
};
There are various ways to do it-
let arr = [{
'obj1': 1
}, {
'obj2': 2
}];
// 1
const arr2 = arr.slice();
console.log(arr2);
// 2
const arr3 = [].concat(arr);
console.log(arr3);
// 3
// or use the new ES6 Spread
const arr4 = [...arr];
console.log(arr4);
// 4
const arr5 = Array.from(arr);
console.log(arr5);
You can achieve this from ES6 spread operators
var arr1 = [1]
var arr2 = arr1
arr1 === arr2 //true
arr2.push(2)
arr2 //[1, 2]
arr1 //[1, 2]
var arr3 = [...arr1] //create a copy of existing array
arr1 === arr3 //false
arr2 === arr3 //false
arr3.push(3)
arr3 //[1, 2, 3]
arr1 //[1, 2]
arr2 //[1, 2]
Same syntax can be used for javascripts object as well
var newObj = [...existingObj]
I'm trying to push some datas into my array.
Actually my code looks like this:
arr.push('step1||item1||99');
It works but it's not the best as I need to split it after to manager datas.
How can I transform this into a multidimensional array ?
What I tried:
arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);
But it doesn't work...
Any help please.
Is there a reason you don't want these individual data points to be objects?
var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);
If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?
Array holds "indexes"
Object holds "Key" and "Value"
Array example:
var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);
Object example:
var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);
Objects in array:
var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;
arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]
maybe you mean something like this
arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);
s is an object, which works just like an array, but is referenced by a string instead of an integer:
s['step'] === 'step1'
s.step === 'step1'
arr[0] === s
Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.