Javascript Auto Increment Array - javascript

Is there a shorthand way to auto increment a Javascript array like you can in PHP?
PHP Example:
$myArray=[];
$myArray[] = [ 'item1' , 'item2' ];
$myArray[] = [ 'item3' , 'item4' ];
JS Example:
let myArray = [];
myArray[ myArray.length ] = [ 'item1' , 'item2' ];
myArray[ myArray.length ] = [ 'item3' , 'item4 '];
//or
myArray.push( [ 'item1' , 'item2' ] );
myArray.push( [ 'item3' , 'item4' ] );
Without using myArray.length or myArray.push()

Here is the ES6 way, using spread operator
const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = [...arr1, ...arr2]; // arr3 ==> [1,2,3,3,4,5]
OR
just by using the concat method
const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = arr1.concat(arr2); // arr3 ==> [1,2,3,3,4,5]

Beside the given answers, you could use Array#splice with a great value for adding the values to the end of the array.
var array = [];
array.splice(Infinity, 0, ...['item1', 'item2']);
array.splice(Infinity, 0, ...['item3', 'item4']);
console.log(array);

There is certainly a way to do exactly the same thing; it even has similar construction:
let arr = ['a', 'b'];
arr = arr.concat([['c', 'd']]);//['a', 'b', ['c', 'd']]
PHP:
<?php
$arr = ["a", "b"];
$arr[] = ["c", "d"];
print_r($arr);
?>
Array
(
[0] => a
[1] => b
[2] => Array
(
[0] => c
[1] => d
)
)

Related

Get array of string from array of array of string in javascript [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 1 year ago.
I have an array of an array of strings like this.
const data = [ ['a' , 'b'] , ['c' , 'd' , 'e'] , ['f'] ]
I want to convert it into an array of strings like this in javascript.
const data = [ 'a' , 'b' , 'c' , 'd' ]
If you want to update the array you'll have to use let instead of const. This will do it.
let data = [ ['a' , 'b'] , ['c' , 'd' , 'e'] , ['f'] ]
data = data.flat()
console.log(data) //["a", "b", "c", "d", "e", "f"]
Look at the docs for this .flat() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
Though if you're going to modify the array, const isn't the way to declare the array.
You can use concat to convert this array
var array = [ ['a' , 'b'] , ['c' , 'd' , 'e'] , ['f'] ];
var UpdatedArray = [];
for(var i = 0; i < array.length; i++)
{
UpdatedArray = UpdatedArray.concat(array[i]);
}
console.log(UpdatedArray);

Find Index where Two Arrays have same Value

If I have two arrays, in Javascript:
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
How can I find the indexes of the larger array where there is a match and store them in another array so example output would be:
let indexes = [3,4]
You could do it by mapping over your search-teams (arr2) and then using the findIndex Method on the source-array (arr1) like this:
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
const result = arr2.map(searchTerm => arr1.findIndex((compareTerm) => compareTerm === searchTerm));
console.log(result);
You can achieve the expected output using Array.map and Array.findIndex
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
const findIndexes = (param1, param2) => {
let arr1 = [...param1];
let arr2 = [...param2];
//swap the arrays if the no.of array elements
//in the second array are greater than first
if(arr1.length < arr2.length) {
[arr1, arr2] = [arr2, arr1];
}
//Loop through all the items of the smaller array
//check if the element is present in the bigger array
return arr2.map(a2 => arr1.findIndex(a1 => a1 === a2));
}
console.log(findIndexes(arr1, arr2));
//here for "test", we'll get index as -1, because
//if the matching element is not found, findIndex will
//return -1
let arr3 = ["Cat", "Goose", "test"];
console.log(findIndexes(arr3, arr1));
If you wish to get the indexes of the elements that are found and wish to filter out all the -1s, below is the code for the same.
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
const findIndexes = (param1, param2) => {
let arr1 = [...param1];
let arr2 = [...param2];
if(arr1.length < arr2.length) {
[arr1, arr2] = [arr2, arr1];
}
return arr2.map(a2 => arr1.findIndex(a1 => a1 === a2)).filter(ele => ele !== -1);
}
console.log(findIndexes(arr1, arr2));
let arr3 = ["Cat", "Goose", "test"];
console.log(findIndexes(arr3, arr1));
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
let indexes = []
arr1.forEach((item, index) => {
if(arr2.includes(item)){
indexes.push(index)
}
})
console.log(indexes)

How to map an array of arrays into an array of objects with a given keys array?

From an array of keys and an array of arrays, like this:
const keys = ['foo', 'bar'];
const vals = [
['a', 'A'],
['b', 'B']
];
How to get an array of objects like below ?
[
{'foo' : 'a', 'bar' : 'A'},
{'foo' : 'b', 'bar' : 'B'}
]
Maybe using lodash ?
You can use loash's _.zipObject() to create an object from an array of keys and values for each value array inside your 2d array using the _.map() method:
const keys = ['foo', 'bar']
const vals = [
['a', 'A'],
['b', 'B']
];
const res = _.map(vals, arr => _.zipObject(keys, arr));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
If you prefer vanilla JS, then you could use Object.fromEntries() on a zipped array (created using .map()):
const keys = ['foo', 'bar']
const vals = [
['a', 'A'],
['b', 'B']
];
const res = vals.map(
arr => Object.fromEntries(arr.map((v, i) => [keys[i], v]))
);
console.log(res);
To be more generic, you can use Array.reduce() with index variable
const keys = ['foo', 'bar']
const values = [
['a', 'A'],
['b', 'B']
]
const mapped = values.map(val => val.reduce((acc, cur, i) => ({...acc, [keys[i]]: cur}),{}))
console.log(mapped)
With lodash/fp you can generate a function using _.flow(), that curries _.zipObject() with the keys, and the _.map() with the curried _.zipObject(), and then you can call it with vals to get the array of objects:
const fn = _.flow(_.zipObject, _.map);
const keys = ['foo', 'bar']
const vals = [
['a', 'A'],
['b', 'B']
];
const result = fn(keys)(vals);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
You can do it simply using reduce.
let keys = ['foo', 'bar'];
let values = [
['a', 'A'],
['b', 'B']
];
const res = values.reduce((a, [first, second]) => {
return [...a, {[keys[0]]: first, [keys[1]]: second}];
}, []);
console.log(res);
.as-console-wrapper{min-height: 100%!important; top:0}
let dataKeys = ['foo', 'bar'];
let dataValues = [
['a', 'A'],
['b', 'B']
];
let transformed = dataValues.reduce((result,item)=>{
result.push(
dataKeys.reduce((r,dk,index)=>{
let o = {};
o[dk]= item[index];
return {...r, ...o}
},{})
)
return result
},[]);
console.log(JSON.stringify(transformed,null,2));

Remove Item from Array using only word

I was wondering how to remove an item from an array only with the world, not array[0], etc.
let input = ['a', 'b', 'c'];
let output = input.filter(item => item !== 'b'); //["a", "c"]
You can use splice method for this and get element position with indexOf
This will remove only first finded element
let testArray = ['1','2','3','4'];
let blackWorld = '2'
if(testArray.includes(blackWorld)) testArray.splice(testArray.indexOf(blackWorld),1)
console.log(testArray) // [ '1', '3', '4' ]
Or use filter method, so it will remove all elements if they equal your value for 1 blackworld
let testArray = ['1','2','3','4','2'];
let blackWorld = "2"
let newArray = testArray.filter(item => item !== blackWorld)
console.log(newArray) // [ '1', '3', '4' ]
For array of blackworlds
let testArray = ['1','2','3','4'];
let blackWorlds = ['1','2']
let newArray = testArray.filter(item => !blackWorlds.includes(item))
console.log(newArray) // [ '3', '4' ]

Is there any shorthand method to convert array of string array with header as first array to Objects of array?

Is there any shorthand method to convert array of string array with header as first array (Input as shown below) to Objects of array (as expected output shown below)
Using for loop we can achieve this, I am looking for any short hand and optimized solution to do this.
Let me know if is there any easy and optimized method to implement this.
Input
[
['fromAge', 'toAge', 'gender', 'institutionalRaf'],
[0, 10, 'F', '1.5'],
[11, 20, 'F', '2.5']
]
Expected Output :
[{
fromAge : 0,
toAge: 10,
gender: "F",
institutionalRaf : "1.5"
},
{
fromAge : 11,
toAge: 20,
gender: "F",
institutionalRaf : "2.5"
}
...
]
You can use map and reudce
Take the first element as header and rest of element as values
Loop through the values array for each element build a object with key from header and value from element
let data = [["fromAge","toAge","gender","institutionalRaf"],["1",'4','m','12'],["4",'12','f','22'],["10",'20','m','109']]
let [header,...values] = data
let final = values.map(v=> {
return v.reduce((op,inp,index)=>{
op[header[index]] = inp
return op
},{})
})
console.log(final)
You could separate the keys and the values and map the value as object with the keys.
var array = [['fromAge', 'toAge', 'gender', 'institutionalRaf'], [0, 10, 'F', '1.5'], [11, 20, 'F', '2.5']],
[keys, ...values] = array,
result = values.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
I'd shift out the first array of keys, then .map to create entries and create the objects using Object.fromEntries:
const arr = [
['a', 'b', 'c'],
[1, 2, 3],
[4, 5, 6]
];
const keys = arr.shift();
const output = arr.map(values =>
Object.fromEntries(
values.map((value, i) => [keys[i], value])
)
);
console.log(output);
Object.fromEntries is a relatively new method. On older environments, either use a polyfill, or create the object with reduce instead:
const arr = [
['a', 'b', 'c'],
[1, 2, 3],
[4, 5, 6]
];
const keys = arr.shift();
const output = arr.map(values => (
values.reduce((a, value, i) => {
a[keys[i]] = value;
return a;
}, {})
));
console.log(output);
If keys are fixed we can use the simple approach like below
let arr=[
['fromAge', 'toAge', 'gender', 'institutionalRaf'],
[0, 10, 'F', '1.5'],
[11, 20, 'F', '2.5']
];
let arr1=arr.slice();
let x=arr1.shift();
let x1=arr1.map(a=>(
{
[x[0]]:a[0],
[x[1]]:a[1],
[x[2]]:a[2],
[x[3]]:a[3],
}
)
)
console.log(x1);
Use destructuring, map and reduce
const array = [
['fromAge', 'toAge', 'gender', 'institutionalRaf'],
[0, 10, 'F', '1.5'],
[11, 20, 'F', '2.5']
]
const [keys, ...values] = array
const result = values.map((value) => value.reduce((a, b, index) => ({...a, [keys[index]]: b}), {}), [])
console.log("result",result)

Categories

Resources