I am just learning Javascript programming and I'm having issues in looping through an array of arrays. I need a coded procedure to go about it.
I want to print out each individual array in the array.
I was trying to use the Map, but once type break it returns the key and value of the first array. I just need a code to help me print out each key and value of every array individually.
var arrOfArr = [
['one', 1],
['two', 2],
['three', 3]
]
var newmap = new Map(arrOfArr)
for (const [key, values] of newmap.entries()) {
newmap.forEach((values, key ) => console.log(key, values))
}
You can simply use a the .forEach method
The forEach() method executes a provided function once for each array element.
This way you can loop through arrOfArr and fill obj with the key/value pairs:
For each array element in arrOfArr you can select the key (first item in the sub array) with e[0] and it's value (second item in the sub array) with e[1].
Then write obj[e[0]] = e[1] to add a new key/value pair in obj
Here is the code:
var arrOfArr = [ ['one', 1], ['two', 2], ['three', 3] ];
const obj = {}
arrOfArr.forEach(e => {
obj[e[0]] = e[1]
})
console.log(obj)
Or if you just want to print them individually, you need obj. Therefore use:
var arrOfArr = [ ['one', 1], ['two', 2], ['three', 3] ];
arrOfArr.forEach( e => console.log(`${e[0]} => ${e[1]}`) )
With ES6 Destructuring assignment you can achieve it with one line:
arrOfArr.forEach(([key, value]) => console.log(key, value));
First, have a look at the below attempt on Node REPL.
Reference: Using iterator on Map() to iterate over keys and values pairs
> var arrOfArr = [
... ['one', 1],
... ['two', 2],
... ['three', 3]
... ]
undefined
>
> var newMap = new Map(arrOfArr)
undefined
> newMap
Map { 'one' => 1, 'two' => 2, 'three' => 3 }
>
> var iteratorObj = newMap[Symbol.iterator]();
undefined
>
> // Printing keys and values
undefined
> for (let item of iteratorObj) {
... console.log(item[0], item[1])
... }
one 1
two 2
three 3
undefined
>
Now, try it online.
var arrOfArr = [
['one', 1],
['two', 2],
['three', 3]
]
var newMap = new Map(arrOfArr)
var iteratorObj = newMap[Symbol.iterator]();
// Printing keys and values
for (let item of iteratorObj) {
console.log(item[0], item[1])
}
arrOfArr is an Array which contains 3 Arrays.
JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1. Using an invalid index number returns undefined.
Useful link : MDN Array
Example:
var arrOfArr = [['one', 1],['two', 2],['three', 3]]
// First array INDEX 0
console.log("First: ", arrOfArr[0]);
// Second array INDEX 1
console.log("Second: ", arrOfArr[1]);
// Third array INDEX 2
console.log("Third: ", arrOfArr[2]);
Related
I currently have two arrays with a bunch of ids. I want to compare the two arrays to see what ids match, then return an array with only the matching ids. I've tried multiple approaches, but nothing seems to work so far. This is what I've done:
const filteredIdArray = array1.filter((item) =>
array2(item)
);
const filteredIdArray = array1.filter(
(item) => array2.indexOf(item) !== -1
);
Both attempts were pulled from other examples, and neither is working. I did make sure that my array1 and array2 were actually arrays not objects. Is there something I'm missing here?
Rephrasing, this is array intersection. A terse, readable, quick (1 pass through each array) is (sort of like this)...
const intersect = (a, b) => {
const setB = new Set(b);
return a.filter(el => setB.has(el));
}
console.log(intersect([1,2,3,4], [3,4,5,6]))
There's ambiguity in the question about whether we're aiming for unique matches. This idea returns all matches, including duplicates. To eliminate those, run the result through a set once more. [...new Set(resultWithDups)]
I think in the first approach it should be array2.includes.
const filteredIdArray = array1.filter((item) => array2.includes(item))
Use a intermediate hash object to hold id's as its key.
That would make it easier to find "duplicates" and push to a result.
arr1 = [1, 2, 3, 4, 0]
arr2 = [3, 4, 5, 6, 0]
result = []
hash = {}
arr1.forEach(item => hash[item] = true)
arr2.forEach(item => hash[item] === true && result.push(item))
console.log(result)
You can use Array#filter and Array#includes methods as follows:
const
arr1 = [2,5,6,8,9,10],
arr2 = [3,4,7,6,8,11],
output = arr1.filter(n => arr2.includes(n));
console.log( output );
Also .....
Your second option should work:
const
arr1 = [2,5,6,8,9,10],
arr2 = [3,4,7,6,8,11],
output = arr1.filter(n => arr2.indexOf(n) !== -1);
console.log( output );
Starting from a 2 dimensional array M
let M = [[1,1],[1,1]];
I would expect the code
let N = Object.assign([], M);
to create a copy of M. In other words to my understanding of Object.assign I should now have two identifiers M,N pointing to different locations in memory, with both locations containing the same 2-dimensional array.
However when I mutate an entry of N, the same entry in M changes as well:
N[0][0] = 0;
console.log(N);
console.log(M);
gives
> Array [Array [0, 1], Array [1, 1]]
> Array [Array [0, 1], Array [1, 1]]
Why is that? A analog example works as expected if M is a list instead of a list of lists.
I tried Array.from() as Andreas suggested, didn't make it work.
I finished creating a deep copy in a custom method:
export function copy(array: any[]): any[] {
const result = Object.assign([], array)
for (let [key, val] of Object.entries(result)) {
if (Array.isArray(val)) {
result[key] = copy(val)
}
}
return result;
}
How can I made new array from firsts elements of arrays from this array ?
[["1",2],["3",2],["6",2]]
and I want it to be
['1', '3', '6']
My attempt:
var newArray = []
for (i = 0; i < arrayToCompare.length - 1; i++) {
newArray.push(arrayToCompare[[0]])
}
You could just use a simple map and destructure the first element:
const arr = [["1", 2],["3", 2],["6", 2]]
console.log(arr.map(([e]) => e))
The ([e]) part of that before the => is destructuring the parameter using array destructuring. It means that for each subarray passed to the map callback, e receives the value of the first element of the subarray. In ES5 and earlier, the ([e]) => e arrow function would be function(entry) { return entry[0]; }
Still, if you still don't understand the concept, prefer efficiency, or just want to go back to basics, you could use the trusty for loop, making sure to push only the first element of each subarray:
const arr = [["1", 2],["3", 2],["6", 2]]
const output = []
for (let i = 0; i < arr.length; i++) {
output.push(arr[i][0])
}
console.log(output)
Try this:
let arr = [["1", 2], ["3", 2], ["6", 2]];
let res = arr.map(val => {
return val[0]
})
console.log(res);
You can use Array.prototype.map() to crate a new array with the item from the first index:
var arr = [["1",2],["3",2],["6",2]]
var newArray = arr.map(i => i[0]);
console.log(newArray);
This one also works
console.log(Object.keys(Object.fromEntries([["1", 2],["3", 2],["6", 2]])))
In this example, Object.fromEntries will create an object from an array of key/value pairs - it will take the first element as a key, and the second element as the value - creating something like this:
{
"1": 2,
"3": 2,
"6": 2
}
Then, Object.values will grab the keys of the object, thus, removing the values and retaining the keys, giving the desired output.
P/S: just added another way to do this
console.log(Array.from([["1", 2],["3", 2],["6", 2]], x=>x[0]))
Use map and get the first element using shift method.
PS: not very efficient because of ...(spread) operator for each element.
const arr = [["1",2],["3",2],["6",2]];
const arrFirsts = arr.map(items => [...items].shift());
console.log(arrFirsts)
console.log(arr)
I have a dataset that looks like this:
[
[a, 10],
[b, 20],
[c, 30],
[d, 40],
["err", NaN],
[a, "foo"],
[b, "foo2"],
[c, "foo3"],
[f, "foo4"]
]
I want to map the first object of each array, if it's repeated set it like this and if it wasn't shown earlier fill with nulls:
[a, 10, "foo"],
[b, 20, "foo2"],
[c, 30, "foo3"],
[d, 40, null ],
[f, null, "foo4"]
I'm using lodash but I'm noob.
Any idea how to get closer is really appreciated.
Using lodash
Start a lodash's chain. Collect arrays to a group by their 1st index using _.groupBy(). Iterate the groups with _.map(), init an item that includes the key (0 index), and nulls. Iterate the group items, and take the 2nd value of the array. Insert the value in the correct place by checking if it's a number (_.isNumber):
var arr = [["a",10],["b",20],["c",30],["d",40],["err",null],["a","foo"],["b","foo2"],["c","foo3"],["f","foo4"]];
var result = _(arr) // start a chain
.groupBy('0') // group by index 0
.map(function(group, key) { // map the groups
var item = [key, null, null]; // init an item
// iterate the group
group.forEach(function(s) {
item[_.isNumber(s[1]) ? 1 : 2] = s[1]; // add the number or the string to the right place
});
return item;
})
.value(); // get the chain value
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Using ES6
Reduce the array to an ES6 Map. For each item, check it it exists in the map, and if not, add if not init an item that includes the key (0 index), and nulls. Place the value in index 1 if it's a number or 2 if it's not. Get the map values iterator, and spread back to an array:
const arr = [["a",10],["b",20],["c",30],["d",40],["err",null],["a","foo"],["b","foo2"],["c","foo3"],["f","foo4"]];
const result = [...arr.reduce((m, [key, value]) => {
// if item doesn't exist in the Map, create a new item
m.has(key) || m.set(key, [key, null, null]);
// get the item from the map, and set the new value in the right place
m.get(key)[typeof value === 'number' ? 1 : 2] = value;
return m;
}, new Map()).values()]; // get the Map's value iterator and spread to an array
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You can do this with Array.prototype.reduce. You'll need to get the first element of the array and, if it's the first time you've encountered it, store it in an index along with its position in the result array. Then add a copy of the array to the result array.
If you've seen the index before, just append the value to the result array. E.g.
// First elements are changed to strings for simplicity
var data = [
['a', 10],
['b', 20],
['c', 30],
['d', 40],
['err', NaN],
['a', "foo"],
['b', "foo2"],
['c', "foo3"],
['f', "foo4"]
];
var result = data.reduce(function(acc, arr){
// Use first element of array as a key. If not seen before, add
// to index object with its index in the data array.
// Then append a copy of the data array.
if (!acc.index.hasOwnProperty(arr[0])) {
acc.index[arr[0]] = acc.data.length;
acc.data.push(arr.slice());
// Otherwise, just append the value to appropriate array in data
} else {
acc.data[acc.index[arr[0]]].push(arr[1]);
}
return acc;
// Required output is in data property
}, {index:{}, data:[]}).data;
console.log(result);
I've changed the variables to strings for simplicity. Just make sure that each variable's value is unique when stringified and is suitable as an object property, otherwise you'll need to use a Map.
This could be somewhat more concise, at the risk of obfuscation.
I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n).
In my Jsx file I have the following:
var items = list.map(i => {
return (
<myview item={i} key={i.id} />
);
});
Then to get the first 3 items I tried
var map = new Map(list);
map.size = 3;
var items = map(i => {
return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
});
This didn't work as map doesn't have a set function. What can I try next?
To get the first n elements of an array, use
const slicedArray = array.slice(0, n);
I believe what you're looking for is:
// ...inside the render() function
var size = 3;
var items = list.slice(0, size).map(i => {
return <myview item={i} key={i.id} />
});
return (
<div>
{items}
</div>
)
arr.length = n
This might be surprising but length property of an array is not only used to get number of array elements but it's also writable and can be used to set array's length MDN link. This will mutate the array.
If you don't care about immutability or don't want to allocate memory i.e. for a game this will be the fastest way.
to empty an array
arr.length = 0
Use Slice Method
The javascript slice() method returns a portion of an array into a new array object selected from start to end where start and end represent the index of items in that array. The original array will not be modified.
syntax : slice(start, end)
Let us say we have an array with 7 items [5,10,15,20,25,30,35] and we want the first 5 elements from that array:
let array = [5,10,15,20,25,30,35]
let newArray = array.slice(0,5)
console.log(newArray)
You can filter using index of array.
var months = ['Jan', 'March', 'April', 'June'];
months = months.filter((month,idx) => idx < 2)
console.log(months);
Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.
In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like
var items = list
.filter((i, index) => (index < 3))
.map((i, index) => {
return (
<myview item={i} key={i.id} />
);
});
Just try this to get first n elements from list:
const slicedList = list.slice(0, n);
Example:
const list = [1,2,3,4,5]
console.log(list.slice(0, 3)) // Should return [1,2,3]
console.log(list.slice(0, 10)) // Returns [1,2,3,4,5] since this is all we have in 1st 10 elements
The following worked for me.
array.slice( where_to_start_deleting, array.length )
Here is an example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2, fruits.length);
//Banana,Orange ->These first two we get as resultant
Using a simple example:
var letters = ["a", "b", "c", "d"];
var letters_02 = letters.slice(0, 2);
console.log(letters_02)
Output: ["a", "b"]
var letters_12 = letters.slice(1, 2);
console.log(letters_12)
Output: ["b"]
Note: slice provides only a shallow copy and DOES NOT modify the original array.
With lodash, take function, you can achieve this by following:
_.take([1, 2, 3]);
// => [1]
_.take([1, 2, 3], 2);
// => [1, 2]
_.take([1, 2, 3], 5);
// => [1, 2, 3]
_.take([1, 2, 3], 0);
// => []
[1,2,3,4,5,6,7,8,8].slice(0, 3) = While return the first 3 elements.
Answer: [1,2,3]
How it works:
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
know more
With LInQer you can do:
Enumerable.from(list).take(3).toArray();
Maybe I'm missing something, but feels like kicking in an open door by suggesting to use splice()? Of course, it's important to remember that this modifies the array.
const myArray = [
'one', 'two', 'three', 'four', 'five', 'six', 'seven',
]
myArray.splice(3)
console.log(myArray)
// expected output: ['one', 'two', 'three']
It's also possible to grab the elements of the array that are outside of what is being kept:
const myArray = [
'one', 'two', 'three', 'four', 'five', 'six', 'seven',
]
const afterFirstThree = myArray.splice(3)
console.log(myArray)
// expected output: ['one', 'two', 'three']
console.log(afterFirstThree)
// expected output: ['four', 'five', 'six', 'seven']
// if n is larger than myArray.length the entire array is kept and if trying to grab the return, it will be an empty array