I am trying to change a specific key's value in json as below :
input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}]
output= [{"201708":10,"201709": 12, "metric":"managedAttrition"},{"201708":10,"201709": 12, "metric":"unmanagedAttrition"},{"201708":10,"201709": 12, "metric":"EndingHeadcount"}]
i have tried looping in the input like input.forEach(element =>{//code})but somewhere iam missing.
This not works??
let input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}]
input.forEach(i=>{
i.metric = 'abc'
})
input.forEach(i=>{
alert(i.metric)
})
I have used spread operator:
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
example:
var a = [1,2,3]
var b = [4,5,6]
a.push(...b)
a //which is [1,2,3,4,5,6]
input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}]
var output = input;
output.forEach(function(currentValue, index, arr){
currentValue.metric = getString(currentValue.metric);
})
function getString(str){
var arr = [];
var arr1 = [];
var isUpperArrived = 0;
if(str.length>0)
{
arr.push(str[0].toUpperCase());
}
for(var i=1;i<str.length;i++)
{
if(str[i]==str[i].toUpperCase())
{
isUpperArrived=1;
arr1.push(str[i].toLowerCase());
}else{
if(!isUpperArrived)
{
arr.push(str[i]);
}else{
arr1.push(str[i]);
}
}
}
//pushing arr using spread operator
arr1.push(...arr);
return arr1.join('');
}
console.log(output);
Related
var arr1 = [1,2,3,4,5];
var arr2 = ["a","b","c","d","e"];
Let's assume that I want to create a list like
1 a
2 b
3 c
4 d
5 e
by using template literal.
let x;
x = document.createElement('li');
x.innerHTML += `<span>${<arr1 index>}</span> <span>${<arr2 index>}</span>`
How can I do that ? Can we use forEach for two arrays in same time ?
This would be more like flatten(zip(arr1, arr2)). There is no built-in zip though you can very easily make it and you can see Array.flat here: MDN: Array.flat.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = ["a", "b", "c", "d", "e"];
const flatten = arr => arr.flat();
const zip = (a, b) => a.map((e, idx) => [e, b[idx]]);
const arr3 = flatten(zip(arr1, arr2));
console.log(arr3);
The answer is "kind of." What you can do is loop through one array with a forEach method, and use the optional argument index to get the value of the second array as well. Something like this:
var arr1 = [1,2,3,4,5];
var arr2 = ["a","b","c","d","e"];
arr1.forEach((value, index) => {
console.log(value);
console.log(arr2[index])
})
But if the data in the two arrays are at all related, you'd want to put the data in the same object, like this:
var arr = [
{
num: 1,
letter: "a"
},
{
num: 2,
letter: "b"
},
{
num: 3,
letter: "c"
}
];
arr.forEach(value => {
console.log(value.num);
console.log(value.letter);
})
Or you would want to use a regular for loop
You could simply use a for() loop instead:
const max = Math.max(arrA.length, arrB.length)
for (let i = 0; i < max; i++) {
const objA = arrA[i],
objB = arrB[i]
if ('undefined' !== typeof objA) {
console.log({ objA })
}
if ('undefined' !== typeof objB) {
console.log({ objB })
}
}
There is no real magic here. You use an index variable, and let it increment:
var arr1 = [1,2,3,4,5];
var arr2 = ["a","b","c","d","e"];
let ul = document.querySelector("ul");
for (let i = 0; i < arr1.length; i++) {
let li = document.createElement('li');
for (let val of [arr1[i], arr2[i]]) {
let span = document.createElement('span');
span.textContent = val;
li.appendChild(span);
}
ul.appendChild(li);
}
<ul></ul>
There are of course other ways to loop, like with forEach, but it comes down to the same principle.
BTW, don't use string literals (template literals) for combining HTML with content, as you might have < or & characters in the content, which really should be escaped. In some cases, not escaping those may lead to unexpected side effects. By creating the elements with createElement and assigning content to their textContent or innerText properties, you avoid those potential issues. Some libraries make it possible to do this with less code, in a more functional way.
As to the initial data: in object oriented languages, like JavaScript, it is better practice to put related values together in one object. In the example, 1 and "a" apparently have a connection, so -- if possible -- you should define the initial data structure as something like this:
var data = [
{ value: 1, name: "a" },
{ value: 2, name: "b" },
{ value: 3, name: "c" },
{ value: 4, name: "d" },
{ value: 5, name: "e" }
];
I want to create an array containing objects that have a key data which is an array of values. I am trying to push values into data but it's not working for me.
My expected result looks like this:
array = [
{ data:[3,2,5] },
{ data:[5,2,1] }
]
So I want to fill the data arrays. To do this, I have tried populating the arrays with a for loop:
var array = [];
for(i=0;i<2;i++){
for(j=0;j<3;j++){
array[i]["data"][j].push(2);
}
}
But this is not working for me.
You can't do this: array[i]["data"][j].push(2) without first initializing array[i].
In your case there's no need to initialize it with an empty array, instead you can simply assign the whole object to each [i]
What you are trying to achieve is an array of objects where each object is of the form {'data': []}
So assume you have your input coming from an array:
const initialData = [[3, 2, 5], [5, 2, 1]];
To get that data in the form you want it, you would do:
const initialData = [[3, 2, 5], [5, 2, 1]];
var array = [];
for(i=0;i < initialData.length; i++){
array[i] = {'data':initialData[i]};
}
console.log(array)
And here is a neater approach using some of Array.prototype's methods which I recommend checking out:
const initialData = [[3, 2, 5], [5, 2, 1]];
const array = initialData.map(elem => {
return {
'data': elem
};
})
console.log(array)
And if you want neaterer you can go with mplungjan's comment
You can initialize the array with: const array = [...Array(2)].map(() => ({ data: [] }));
Then you'll be able to access it with:
for(i=0; i<2; i++){
for(j=0;j<3;j++){
array[i].data[j] = 2;
}
}
Take a look at these changes, which modify your existing code. For an improved method, see the bottom
Your Code
var array = [];
for(i=0;i<2;i++){
array.push({data:[]}) // create your object
for(j=0;j<3;j++){
array[i]["data"].push(2); // you don't need '[j]' because the result of 'data' key is an array, so just push onto it
}
}
console.log(array)
Alternative Method
let arr = [...new Array(2)].map(el=>({ data: new Array(3).fill(2) }));
console.log(arr)
You could do something like this:
let items = 2
let arr = Array.from({ length: items }, (item) => item = { data: [] })
for (let i = 0; i < items; i++) {
for (let j = 0; j < 3; j++) {
let val = 2 // replace value here
arr[i].data.push(val)
}
}
console.log(arr);
I want to return an array containing all the elements of the array located at the given key that are equal to ten. It should print out [10, 10] but the result of my code is [ 10, 10 ] with extra space in the front and back or my code is just wrong.
var obj = {
key: [1000, 10, 50, 10],
key2: [],
key3: "abc"
};
function isValid(obj, key) {
var result = [];
if (!obj.hasOwnProperty("key") ||
!Array.isArray(obj[key]) ||
obj[key].length === 0) {
return []; //return empty array if those condition meet.
}
else {
for (var i = 0; i < obj[key].length; i++) {
if (obj[key][i] === 10) {
result.push(obj[key][i]); //push the 10 to result empty array.
}
}
return result;
}
}
var output = isValid(obj, 'key');
console.log(output); // --> should print out [10, 10]
It may be a problem with your browser. Space seperating contents in an array automatically removed when you iterate through it. Some browsers add a space between each entry for visual improvement. As you are using a number array, the space will not affect your normal code execution.
I have 10 different arrays. Each array has different numbers.
array1 = [1,2,3,4,5]
array2 = [6,7,8,9,10]
...
array 10 = [51,52,53,54]
let's say I pass in 7. Then I want to know which array it is from and want to return array number. So in this case it is going to be 2.
Should I write a switch statement for each array? Appreciate it in javascript.
try:
var arrays = [array1, array2, ..., array10];
for(var i=0; i<arrays.length; ++i) {
if (arrays[i].indexOf(value) != -1) {
console.log('found in array' + (i+1));
}
}
You cannot directly retrieve the name of array.The reason is this variable is only storing a reference to the object.
Instead you can have a key inside the same array which represent its name. Then indexOf can be used to find the array which contain the number , & if it is so, then get the array name
var array1 = [1,2,3,4,5];
array1.name ="array1";
var array2 = [6,7,8,9,10];
array2.name ="array2";
var array10 = [51,52,53,54]
array10.name ="array10";
var parArray = [array1,array2,array10]
function _getArrayName(number){
for(var o=0;o<parArray.length;o++){
var _tem = parArray[o];
if(parArray[o].indexOf(number) !==-1){
console.log(parArray[o].name);
}
}
}
_getArrayName(6) //prints array2
jsfiddle
One fast method should be using hash tables or as i would like to call LUT. Accordingly this job boils down to a single liner as follows;
var arrs = {
arr1 : [1,2,3,4,5],
arr2 : [6,7,8,9,10],
arr3 : [12,14,16,17],
arr4 : [21,23,24,25,27,20],
arr5 : [31,34,35,39],
arr6 : [45,46,44],
arr7 : [58,59],
arr8 : [66,67,69,61],
arr9 : [72,73,75,79,71],
arr0 : [81,85,98,99,90,80]
},
lut = Object.keys(arrs).reduce((p,c) => {arrs[c].forEach(n => p[n]=c); return p},{}),
findar = n => lut[n];
document.write("<pre>" + findar(12) + "</pre>");
One way to do this is have the arrays in an object and iterate over the keys/values. This method doesn't presume the arrays (and therefore their names) are in sequential order.
Note: this will always return a the first match from the function and terminate the search.
var obj = {
array1: [1, 2, 3, 4, 5],
array2: [6, 7, 8, 9, 10],
array3: [51, 52, 53, 54],
array4: [51, 52, 53, 54, 7]
}
function finder(obj, test) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj[key].indexOf(test) > -1) {
return key.match(/\d+/)[0];
}
}
return false;
}
finder(obj, 7); // '2'
DEMO
If you want to find all instances of a value in all arrays the function needs to be altered slightly.
function finder(obj, test) {
var keys = Object.keys(obj);
var out = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj[key].indexOf(test) > -1) {
out.push(key.match(/\d+/)[0]);
}
}
return out;
}
finder(obj, 7); // ['2', '4']
DEMO
I have two arrays. How can I join them into one multidimensional array?
The first array is:
var arrayA = ['Jhon, kend, 12, 62626262662',
'Lisa, Ann, 43, 672536452',
'Sophie, Lynn, 23, 636366363'];
My other array has the values:
var arrayB = ['Jhon', 'Lisa', 'Sophie'];
How could I get an array with this format??
var jarray = [['Jhon', ['Jhon, kend, 12, 62626262662']],
['Lisa', ['Lisa, Ann, 43, 672536452']],
['Sohphie', ['Sophie, Lynn, 23, 636366363']]]
var jarray = [];
for (var i=0; i<arrayA.length && i<arrayB.length; i++)
jarray[i] = [arrayB[i], [arrayA[i]]];
However, I wouldn't call that "multidimensional array" - that usually refers to arrays that include items of the same type. Also I'm not sure why you want the second part of your arrays be an one-element array.
Here is a map version
const arrayA = ['Jhon, kend, 12, 62626262662',
'Lisa, Ann, 43, 672536452',
'Sophie, Lynn, 23, 636366363'];
const arrayB = ['Jhon', 'Lisa', 'Sophie'];
/* expected output
var jarray = [['Jhon', ['Jhon, kend, 12, 62626262662']],
['Lisa', ['Lisa, Ann, 43, 672536452']],
['Sohphie', ['Sophie, Lynn, 23, 636366363']]] */
const jarray = arrayB.map((item,i) => [item,[arrayA[i]]]);
console.log(jarray);
You can use Underscore.js http://underscorejs.org/#find
Looks through each value in the list, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2
Then, you can make the same with the array B elements and by code, make a join.
This is what I did to get what you were asking:
var jarray = [];
for (var i = 0; i < arrayB.length; i++) {
jarray[i] = [];
jarray[i].push(arrayB[i]);
var valuesList = [],
comparator = new RegExp(arrayB[i]);
for (var e = 0; e < arrayA.length; e++) {
if (comparator.test(arrayA[e])) {
valuesList.push(arrayA[e]);
}
}
jarray[i].push(valuesList);
}