I have an array inside another array:
Structure:
First Array
[
{
Second Array
[
{
}
]
}
]
So I want to replace all Second Array for new array that I have so I try this:
this.FirstArray.map(
(myArray) =>
myArray.SecondArray === this.MyNewArray
)
But this is not replacing for my new array it still having old values.
What am I doing wrong?
You can achieve that by using spread operator and without any loop as you want to replace second array with the new array.
Input array :
First Array
[{
Second Array
[{}]
}]
Logic to replace newArray with secondArray :
FirstArray[0].secondArray = [ ...newArray ]
Demo :
const firstArray = [{
secondArray: ['alpha', 'beta', 'gamma']
}];
const newArray = ['A', 'B'];
firstArray[0].secondArray = [ ...newArray ];
console.log(firstArray);
Normally, the map() method will return a new array.
// Assume that your nested array looks like so:
let nestedArray = [
["A", "B", "C"],
["E", "F", "G"]
]
// Assume that this is the new array
const newArray = [1, 2, 3]
nestedArray = nestedArray.map(el => newArray);
// expected output: nestedArray [[1, 2, 3], [1, 2, 3]]
Related
I have an array of elements I want to map to a new array of objects with a key as a name.
let array = ["abc", "def", "xyx"]
Expected Output
let array1 = [{name: "abc"}, {name: "def"}, {name: "xyz"}]
You can use array.map:
let newArray = array1.map((value) => ({name: value});
let arr = ['a', 'b', 'c'];
let newArr = arr.map(el => ({ name: el }));
console.log(newArr);
you can use map() function for that,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
let array = ["abc", "def", "xyx"]
const array1 = array.map( data => {
return {name:data}
})
/* this code will also work,if you dint specify the properties name
by default it will be the variable's name. In this case 'name' */
const array2 = array.map( name => {
return {name}
})
console.log(array1)
console.log(array2)
I have an array of objects with the following format. Each object has got few properties and also an array. I have to fetch a property if a key is present in the array.
Consider the below object: When I give key as 7 it should return me 'xyz'. If key is 3 it should give me 'abc'
[
{
val : 'abc',
arr : [1,2,3,4]
},
{
val: 'xyz',
arr : [7,8,9]
}
]
You can use find() and includes(). Use find of the main array and check if the arr of that object includes() the given key. return the val property of the found object.
const arr = [
{
val : 'abc',
arr : [1,2,3,4]
},
{
val: 'xyz',
arr : [7,8,9]
}
]
const getVal = (arr,key) => (arr.find(x => x.arr.includes(key)) || {}).val;
console.log(getVal(arr,3))
console.log(getVal(arr,7))
You can use Array.filter() to filter the object which meets the condition whereby the element (7) exists in the array. Within the callback function for Array.some(), you can use Array.includes() to check if the element (7), exists in the arr property itself:
const data = [
{
val : 'abc',
arr : [1,2,3,4]
},
{
val: 'xyz',
arr : [7,8,9]
}
]
const res = data.filter(obj => obj.arr.includes(7))[0].val;
console.log(res);
You can try this too.
var x = [{
val: 'abc',
arr: [1, 2, 3, 4]
},
{
val: 'xyz',
arr: [7, 8, 9]
}
];
var test = function(data, key) {
for (let i of x) {
if (i.arr.indexOf(key) >= 0)
return i.val;
}
}
// example
console.log(test(x,9));
I have an array that looks like:
[
["A","B","C","D"],
["E","F","G","H"],
[6,43,2,4]
]
I want to sort this array in descending order of the items in the third row, such that it looks like:
[
["B","A","D","C"],
["F","E","H","G"],
[43,6,4,2]
]
So far this is what I wrote:
var arr = [
["A","B","C","D"],
["E","F","G","H"],
[6,43,2,4]
]
arr = arr.sort((a,b) => {
return b[2] - a[2]
});
console.log(arr);
But the array does not get sorted. Where did I go wrong?
You could take the indices of the array for sorting, sort this array by the values of the original array and map all reordered items.
var array = [["A", "B", "C", "D"], ["E", "F", "G", "H"], [6, 43, 2, 4]],
indices = [...array[2].keys()].sort((a, b) => array[2][b] - array[2][a]);
array = array.map(a => indices.map(i => a[i]));
console.log(array.map(a => a.join(' ')));
You want to sort columns. It is easier to sort rows. So, you could transpose then sort then retranspose:
const arr = [
["A","B","C","D"],
["E","F","G","H"],
[6,43,2,4]
];
const transpose = array => array[0].map((col, i) => array.map(row => row[i]));
const t = transpose(arr);
t.sort((rowi,rowj) => (rowj[rowj.length - 1] - rowi[rowi.length-1]));
console.log(transpose(t));
Which has the intended output of:
[ [ 'B', 'A', 'D', 'C' ],
[ 'F', 'E', 'H', 'G' ],
[ 43, 6, 4, 2 ] ]
This is clearly not as efficient as the other answers, but the fact that you are asking the question suggests that your current way of storing the data isn't convenient for your purposes. Perhaps you might want to transpose then skip the retranspose part.
You need to first sort the number store indexes and then sort the other arrays.
var arr = [
["A","B","C","D"],
["E","F","G","H"],
[6,43,2,4]
]
var tmp = arr[2].map((value, i) => ({value, i})).sort((a, b) => b.value - a.value);
arr = arr.map(function(arr) {
return tmp.map(({value, i}) => arr[i]);
});
console.log(arr);
It would be easier if you could depict the data differently. The Array.sort function will not help you with your current example.
var arr = [{
a: "A", b: "E", c: 6
},{
a: "B", b: "F", c: 43
},{
a: "C", b: "G", c: 2
},{
a: "D", b: "H", c: 4
}]
arr.sort((a, b) => {
return b.c - a.c;
})
console.log(arr);
If you can't, I could provide a different answer; but the answer would be very inefficient.
I have an array of values, for example:
let values = [1, 2, 3, 4, 5];
And I have another array, containing objects, for example:
let objects = [{name: 'Dennis', value: 2}, {name: 'Charlie', value: 4}];
I would like to produce an array that only contains values that aren't present in the value property of my objects.
So from the examples above, I would return an array of [1, 3, 5]
What I've got at the moment is:
let missingValues = [];
for (let i = 0; i < values.length; i++) {
if (!objects.filter(obj => obj.value === values[i]) {
missingValues.push(values[i]);
}
}
This works, but feels slightly messy, is there a more efficient way to do this?
You could filter the values with a look up in the objects array.
var values = [1, 2, 3, 4, 5],
objects = [{ name: 'Dennis', value: 2 }, { name: 'Charlie', value: 4 }],
result = values.filter(v => !objects.find(({ value }) => value === v));
console.log(result);
...is there a more efficient way to do this?
I assume you really mean "efficient" (as opposed to "concise").
Yes, you can build an object or Set containing the values from the second array, and then use that to filter instead:
let values = [1, 2, 3, 4, 5];
let objects = [{name: 'Dennis', value: 2}, {name: 'Charlie', value: 4}];
let valueSet = new Set();
for (const obj of objects) {
valueSet.add(obj.value);
}
let missingValues = values.filter(value => !valueSet.has(value));
console.log(missingValues);
(You can also use an object for the same thing, if you prefer. let valueSet = Object.create(null); then valueSet[value] = true and !valueSet[value].)
This is only worth doing if the product of the arrays is quite large (hundreds of thousands of entries) or you're doing this a lot.
I'd love an explanation as to why the result of this function don't match my expectation.
const numbers = [ 1, 2 ]
const objects = [{f: 'a'}, {f: 'b'}]
async function(domain) {
let matrix = []
objects.forEach((object) => {
numbers.forEach((number) => {
object.number = number
matrix.push(object)
})
})
return matrix
}()
Actual
The result, once the promise is resolved returns:
[
{ f: 'a', number: 2 },
{ f: 'a', number: 2 },
{ f: 'b', number: 2 },
{ f: 'b', number: 2 }
]
Expected
But, my expectation is that it would return:
[
{ f: 'a', number: 1 },
{ f: 'a', number: 2 },
{ f: 'b', number: 1 },
{ f: 'b', number: 2 }
]
One of the things that puzzles me the most is that if I console.log the value of object just before I push, it logs out each of the objects in my expected result.
Because objects are passed by reference and you are modifying original object, instead you can push new object.
const numbers = [ 1, 2 ]
const objects = [{f: 'a'}, {f: 'b'}]
let matrix = []
objects.forEach((object) => {
numbers.forEach((number) => {
matrix.push({...object, number})
})
})
console.log(matrix)
Use Array.flatMap() to iterate the objects, with a nested Array.map() to iterate the numbers and return an array of new objects with the relevant number. The flatMap will flatten the arrays produced by the map to a single array:
const numbers = [ 1, 2 ]
const objects = [{f: 'a'}, {f: 'b'}]
const matrix = objects.flatMap(o => // map the objects and flatten
numbers.map( // map the numbers
number => ({ ...o, number }) // return a new object with the number
)
);
console.log(matrix);
Old answer:
Use nested Array#map to iterate the objects and the numbers, and Object#assign to create new objects that include the relevant number. Flatten resulting nested arrays by using the spread syntax in Array#concat:
const numbers = [ 1, 2 ]
const objects = [{f: 'a'}, {f: 'b'}]
const matrix = [].concat(... // flatten the nested arrays
objects.map((o) => // map the objects
numbers.map( // map the numbers
(number) => Object.assign({}, o, { number }) // return a new object with the number
)
));
console.log(matrix);
#Nenad is correct. You can also do it with reduce and map.
const numbers = [ 1, 2 ];
const objects = [{f: 'a'}, {f: 'b'}];
const matrix = numbers.reduce((acc, nxt) => {
const numberedObjs = objects.map(obj => ({...obj, number:nxt}));
acc.push(...numberedObjs);
return acc;
}, []);