×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

How to create a matrix of all ones in JavaScript?

By IncludeHelp Last updated : January 27, 2024

Problem statement

Write JavaScript code to create a matrix of all ones.

Creating a matrix of all ones

To create a matrix of all one, first, create an array for rows and then use the fill() method of the Array object by passing 1 as its argument. Use the fill() method inside a loop to create a subarray with these elements and assign the subarrays as the elements of the main array.

Syntax

Below is the syntax to create a matrix of all ones in JavaScript:

Array(N).fill(1);

Here, N is the total number of elements.

JavaScript code creates a matrix of all one

This example creates a matrix of all ones.

const rows = 3;
const cols = 3;

// Create array for rows
const matrix = new Array(rows);
for (let i = 0; i < matrix.length; i++) {
  // Arrays of size 4 and filled of 1
  // Adding it into the matrix as an element
  matrix[i] = new Array(4).fill(1);
}

// printing matrix
console.log(matrix);

Output

The output of the above code is:

[ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ]
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.